I have a chrome extension that activates on certain websites and injects elements into the HTML DOM. Now, I am looking to integrate Google Tag Manager into the extension.
In the Google Tag Manager documentation, it instructs to add a specific function in the <head>
tag of the page. Initially, I attempted to add the script tag to the document's <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);
}
However, when I tried to connect through Google Tag Assistant, it was unsuccessful.
Subsequently, I experimented with running the script instead of adding it to the head tag. I created a new file named gtm.js
and included the script within 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();
Yet again, after attempting to connect through Tag Assistant, there was no success.
If anyone has any insights or experience in this area, I would greatly appreciate some guidance. Thank you!