Google Tag Manager - injectScript API never runs callbacks

Viewed 572

I'm using the injectScript API in Google Tag Manager in a tag template, but I just cannot get it to fire any callback functions for when the external script loads (or fails to load). Any ideas please?

My template is thus, with an inject script permission defined for: https://www.google-analytics.com/analytics.js

Code:

// load APIs
const logToConsole = require('logToConsole');
const injectScript = require('injectScript');
const queryPermission = require('queryPermission');

// script url
const url = 'https://www.google-analytics.com/analytics.js';

// Callback to note if script load succeeded
const onSuccess = () => {
  logToConsole('Script LOADED');
  data.gtmOnSuccess();
};

// Callback to note if script load failed
const onFail = () => {
  logToConsole('Script load FAILED.');
  data.gtmOnFailure();
};

// Check permission and load script
logToConsole('Checking permission to load script:' + url);
if (queryPermission('inject_script', url)) {
  logToConsole('Permission check: OK');
  injectScript(url, onSuccess, onFail, url);
} else {
  logToConsole('Permission check: FAIL');
  data.gtmOnFailure();
}

The log in GTM shows this. Nothing logged from the callback functions for success/fail.

Template preview refreshed at 25/06/2020, 13:15:45
Test started
Checking permission to load script:https://www.google-analytics.com/analytics.js
Permission check: OK
Executed 1 test (SUCCESS)

Any ideas why the callbacks are not happening? I do see analytics.js loading in my chrome console network tab.

I've tried a bunch of variations and sample code of similar examples, and they don't work. I'm running Chrome (Version 83.0.4103.116 (Official Build) (64-bit)). I have Ghostery plugin but its disabled. I also repeated the test in Microsoft Edge and got the same result.

Thanks!

1 Answers

The callback functions supplied to injectScript DO run, but the logToConsole does not produce logging output when executed within those functions.

So if you are relying on seeing logging to know if your functions are being called successfully and what they are doing, you will not know whats going on.

The workaround I used was that instead of logging to console within those functions I would use sendPixel to call a fake URL with my logged message as a GET parameter. E.g. www.testabcd12345.com/index.html?msg=my-logged-message

Then I could observe those within my Chrome console Network tab. This is horrible but it worked enough.

Also gtmOnSuccess seemed to have similar limitations.

Related