简体   繁体   中英

How can I add Google Tag Manager to chrome extension content-scripts?

I have a chrome extension that activates on some websites and injects some elements in html DOM. Now I want to add Google Tag Manager on the extension.

In the Google Tag Manager documents it's mentioned to add the given function in the page <head> tag. So first I tried to add the script tag in document <head> tag as soon as the extension is loaded:

const loadGTM = () => {
  const scriptTag = document.createElement("script");
  scriptTag.innerHTML = `(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':
  new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],
  j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=
  'https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);
  })(window,document,'script','dataLayer','GTM-XXXXXXX');`;
  document.head.appendChild(scriptTag);

  const noScriptTag = document.createElement("noscript");
  noScriptTag.innerHTML = `<iframe src="https://www.googletagmanager.com/ns.html?id=GTM-XXXXXXX"
  height="0" width="0" style="display:none;visibility:hidden"></iframe>`;
  document.body.prepend(noScriptTag);
}

Then I tried to connect through Google Tag Assistant and it didn't.

After this I tried to run the script instead of adding the script to head tag. So I open a new gtm.js file and added the script in it:

//gtm.js
const accountToken = `GTM-XXXXXXX`;
function integrateGTM() {
  (function (w, d, s, l, i) {
    w[l] = w[l] || [];
    w[l].push({ "gtm.start": new Date().getTime(), event: "gtm.js" });
    var f = d.getElementsByTagName(s)[0],
      j = d.createElement(s),
      dl = l != "dataLayer" ? "&l=" + l : "";
    j.async = true;
    j.src = "https://www.googletagmanager.com/gtm.js?id=" + i + dl;
    f.parentNode.insertBefore(j, f);
  })(window, document, "script", "dataLayer", accountToken);
  const code = `<noscript><iframe src="https://www.googletagmanager.com/ns.html?id=${accountToken}"
  height="0" width="0" style="display:none;visibility:hidden"></iframe></noscript>`;
  const bodyScript = document.createElement("noscript");
  bodyScript.innerHTML = code;
  document.body.prepend(bodyScript);
}

integrateGTM();

And again after trying to connect through Tag Assistant it doesn't connect.

So If anybody has any idea or experience in this field I would be glad to get some help. Thank you!

I am not sure about google tag manager, but you can send requests directly to google analytics.

You can make a post fetch request from your content script like so:

const trackEvent = (category, action, label, value) => {
const data = {
// API Version.
v: '1',
// Tracking ID / Property ID.
tid: GA_TRACKING_ID,
// Anonymous Client Identifier. Ideally, this should be a UUID that
// is associated with particular user, device, or browser instance.
cid: '555',
// Event hit type.
t: 'event',
// Event category.
ec: category,
// Event action.
ea: action,
// Event label.
el: label,
// Event value.
ev: value,
};

return fetch('http://www.google-analytics.com/debug/collect', {
 params: data,
});
}

You may have to add headers to spoof that it is coming from a browser:

headers: {
    'user-agent':
      'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36',
  },

You can also make a get request like so:

'https://www.google-analytics.com/collect?v=1&t={category}&tid=${GA_TRACKING_ID}&cid=555&dp=tube'

https://developers.google.com/analytics/devguides/collection/protocol/v1/reference#overview

Call in the script like:

try {
await trackEvent(
  'Example category',
  'Example action',
  'Example label',
  '100'
);
return 'Event tracked.');
} catch (error) {
 // handle error
}

see: https://cloud.google.com/appengine/docs/standard/integrating-with-analytics?tab=node.js#top

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM