Reputation: 53
I am trying to block google analytics in javascript when a user don't want to get cookies.
if (want_cookie != "no"){
/* load google analytics script */
}
But I didn't find how to load this script in javascript ...
<script async src="https://www.googletagmanager.com/gtag/js?id=UA-XXXXXX"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'UA-XXXXXX');
</script>
Upvotes: 5
Views: 4482
Reputation: 2205
Building on top of the accepted answer, I implemented it like this:
HTML:
<button id="declineButton">Decline</button>
<button id="acceptButton">Accept</button>
JS for declining:
declineButton.addEventListener("click", () => {
window["ga-disable-G-XXXX"] = true; // replace G-XXXX with your id
});
JS for accepting:
acceptButton.addEventListener("click", () => {
window["ga-disable-G-XXXX"] = false; // replace G-XXXX with your id
appendScriptToHead();
executeGoogleAnalyticsScript();
});
function appendScriptToHead() {
const script = document.createElement("script");
script.type = "text/javascript";
script.async = true;
script.src = "https://www.googletagmanager.com/gtag/js?id=G-XXXX"; // replace G-XXXX with your ID
document.head.appendChild(script);
}
function executeGoogleAnalyticsScript() {
window.dataLayer = window.dataLayer || [];
function gtag() {
dataLayer.push(arguments);
}
gtag("js", new Date());
gtag("config", "G-XXXX"); // replace G-XXXX with your id
}
Note:
According to the documentation we have to make sure that the disabling (setting the window property) is done before the gtag()
is executed.
Upvotes: 0
Reputation: 193
Try something like this:
if (want_cookie != "no"){
var newScript = document.createElement("script");
newScript.type = "text/javascript";
newScript.setAttribute("async", "true");
newScript.setAttribute("src", "https://www.googletagmanager.com/gtag/js?id=UA-XXXXXX");
document.documentElement.firstChild.appendChild(newScript);
}
So what I did is after checking if user agree on cookies dynamically create script element and append it to page.
Upvotes: 9