Por alguna razón, Google Tags Manager no carga ninguna cookie cuando se agrega dinámicamente
Cuando el usuario hace clic en algún botón de aceptar, agrego una etiqueta de secuencia de script al body con el src de https://www.googletagmanager.com/gtag/js?id=${GOOGLE_TAGS_ID} y después de que se haya cargado ejecuté esto:
function gtag(...args: any[]) { window.dataLayer.push(args); } // After the script has finish loading I called this function function load() { gtag('js', new Date()); gtag('config', GOOGLE_TAGS_ID); }gtag debe ser global y usar el objeto de arguments El problema fue la función gtag que definí.
El código que deberías agregar a tu página HTML era este:
<!-- Global site tag (gtag.js) - Google Analytics --> <script async src="https://www.googletagmanager.com/gtag/js?id=<id>"></script> <script> window.dataLayer = window.dataLayer || []; function gtag(){ dataLayer.push(arguments);} gtag('js', new Date()); gtag('config', '<id>'); </script>gtag :No era global (tal vez no fue un problema, pero es diferente a la implementación original).
Usé los parámetros de descanso ( ...args ) en lugar de usar el objeto de arguments .
Porque los parámetros de descanso y el objeto de arguments no son lo mismo, como se explica en MDN - La diferencia entre los parámetros de descanso y el objeto de argumentos
En la mayoría de las circunstancias, debería preferir usar los parámetros de descanso sobre el objeto de arguments , pero aparentemente, Google Tags Manager necesita las propiedades del objeto de arguments .
Entonces lo que hice fue:
// The function is usually done in the script tag within the global scope, so we adding the function to the global scope window.gtag = function gtag(...args: any[]) { // The original function was without the ...args, we added it so TypeScript won't scream // Use arguments instead of the rest parameter // See why here - https://stackoverflow.com/a/69185535/5923666 // TL;DR: arguments contain some data that not passed in the rest parameters window.dataLayer.push(arguments); }