admin管理员组

文章数量:1302274

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=""></script>
<script>
  window.dataLayer = window.dataLayer || [];
  function gtag(){dataLayer.push(arguments);}
  gtag('js', new Date());

  gtag('config', 'UA-XXXXXX');
</script>

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./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>
Share Improve this question asked Jul 3, 2018 at 12:24 Arthur HArthur H 531 silver badge5 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 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./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.

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./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.

本文标签: cookiesHow to load gtagjs (Google analytics) dynamically in javascriptStack Overflow