【问题标题】:Google tags manager don't load any cookies谷歌标签管理器不加载任何 cookie
【发布时间】:2021-09-14 23:34:05
【问题描述】:

由于某种原因,Google 标签管理器在动态添加时不会加载任何 cookie

当用户点击某个接受按钮时,我将 script 标记添加到 bodysrchttps://www.googletagmanager.com/gtag/js?id=${GOOGLE_TAGS_ID} 并在加载后运行:

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);
}

【问题讨论】:

    标签: javascript typescript google-analytics google-tag-manager


    【解决方案1】:

    TL;DR gtag 函数应该是全局的并使用 arguments 对象


    问题是我定义的gtag 函数

    您应该添加到 HTML 页面的代码如下:

    <!-- 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 函数遇到的2 个问题:

    1. 它不是全局的(也许不是问题,但它与原始实现不同)。

    2. 我使用了rest parameters (...args) 而不是使用arguments 对象。

      因为rest参数和arguments对象不一样,在MDN - The difference between rest parameters and the arguments object有解释

    在大多数情况下,您应该更喜欢使用其余参数而不是 arguments 对象,但显然,Google 标记管理器 需要 arguments 对象的属性。

    所以我做的是:

    // 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);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-02
      • 1970-01-01
      • 1970-01-01
      • 2018-04-13
      • 1970-01-01
      相关资源
      最近更新 更多