Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

340
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda