5

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>

2 Answers 2

9

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.

Sign up to request clarification or add additional context in comments.

2 Comments

This seems to replace the first <script> but what about the second one?
beware, document.documentElement.firstChild does not necessarily refer to the <head>element!
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.