谷歌标签管理器不加载任何饼干



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

当用户点击一些接受按钮时,我用https://www.googletagmanager.com/gtag/js?id=${GOOGLE_TAGS_ID}srcbody添加一个script标签,在它加载后,我运行这个:

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. 我使用其余参数(...args)而不是使用arguments对象。

    因为rest形参和arguments对象不一样,正如MDN中所解释的——rest形参和参数对象

    的区别

在大多数情况下,您应该更喜欢使用arguments对象的其余参数,但显然,Google Tags Manager需要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);
}

相关内容

最新更新