Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

341
Visualizações
Dynamically Adding Google Analytics and Data Layer On Accept Cookies

I am trying to add Google Analytics to my site dynamically only after the use clicks "I Accept Cookies".

The script that I have so far is

<script>
  function addScript() {
    var addGoogleAnalytics = document.createElement("script");
    addGoogleAnalytics.setAttribute("src","https://www.googletagmanager.com/gtag/js?id=G-MYIDHERE");
    addGoogleAnalytics.async = "true";
    document.head.appendChild(addGoogleAnalytics);

    var addDataLayer = document.createElement("script");
    var dataLayerData = document.createTextNode("window.dataLayer = window.dataLayer || []; \n function gtag(){dataLayer.push(arguments);} \n gtag('js', new Date()); \n gtag('config', 'G-MYIDHERE');");
    addDataLayer.appendChild(dataLayerData);
    document.head.appendChild(addDataLayer);
  }
</script>

This is triggered using a simple

<a href="#" onclick="addScript();">Click Here</a>

This seems to work fine, but my questions are:

  1. Is there a better way to do this? I am no expert at javascript, so I am a little surprised it works and want to make sure there are no major code/security risks before deploying.

  2. More importantly.. How do I store the "I accept" in a cookie or localStorage so that they do not have to click I accept each time, and if that is set it loads the script automatically without the onclick function?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

So the problem with the above was that the code showed the cookie notice on every page.

<script>
var cookies = localStorage.getItem("cookiesAccepted");
// this checks if cookies local storage was accepted before
if(cookies == 'Yes') {

//if they were it creates the analytics tag

    var addGoogleAnalytics = document.createElement("script");
    addGoogleAnalytics.setAttribute("src","https://www.googletagmanager.com/gtag/js?id=G-MYIDHERE");
    addGoogleAnalytics.async = "true";
    document.head.appendChild(addGoogleAnalytics);

    var addDataLayer = document.createElement("script");
    var dataLayerData = document.createTextNode("window.dataLayer = window.dataLayer || []; \n function gtag(){dataLayer.push(arguments);} \n gtag('js', new Date()); \n gtag('config', 'G-MYIDHERE');");
    addDataLayer.appendChild(dataLayerData);
    document.head.appendChild(addDataLayer);
}

//if cookies were not set to yes, it waits for the cookie banner click function.

function addScript() {
    localStorage.setItem('cookieAccepted', 'Yes');
    var addGoogleAnalytics = document.createElement("script");
    addGoogleAnalytics.setAttribute("src","https://www.googletagmanager.com/gtag/js?id=G-MYIDHERE");
    addGoogleAnalytics.async = "true";
    document.head.appendChild(addGoogleAnalytics);

    var addDataLayer = document.createElement("script");
    var dataLayerData = document.createTextNode("window.dataLayer = window.dataLayer || []; \n function gtag(){dataLayer.push(arguments);} \n gtag('js', new Date()); \n gtag('config', 'G-MYIDHERE');");
    addDataLayer.appendChild(dataLayerData);
    document.head.appendChild(addDataLayer);
  }
</script>

This code above seems to work. If the user already accepted cookies it adds the Google Analytics tag without prompting the user. If they have not accepted the prompt is used to trigger the addscript function on accept.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda