谷歌标签管理器不加载任何Cookie [英] Google tags manager don't load any cookies

查看:17
本文介绍了谷歌标签管理器不加载任何Cookie的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于某种原因,动态添加Google Tages Manager时不会加载任何Cookie

当用户单击某个接受按钮时,我使用srcsrcscript标记添加到body,并在加载后运行以下命令:

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

推荐答案

tl;drgtag函数应为全局函数,并使用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

    所述

在大多数情况下,您应该优先使用REST参数而不是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);
}

这篇关于谷歌标签管理器不加载任何Cookie的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆