Google tags manager don#39;t load any cookies(谷歌标签管理器不加载任何Cookie)
问题描述
由于某种原因,动态添加Google Tages Manager时不会加载任何Cookie
当用户单击某个接受按钮时,我使用src的src将script标记添加到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个问题:
它不是全局的(可能不是问题,但与原始实现不同)。
我使用的是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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:谷歌标签管理器不加载任何Cookie
基础教程推荐
- 从快速中间件中排除路由 2022-01-01
- 使用 jQuery 在悬停时交换 DIV 类 2022-01-01
- 在 Javascript 中使用 Fetch API 上传文件并显示进度 2022-01-01
- 带角度的选项卡:仅使用 $http 在单击时加载选项卡 2022-01-01
- 逻辑运算符 ||在 javascript 中,0 代表 Boolean false? 2022-01-01
- 当木偶师打开Chrome时,不能使用Chrome扩展 2022-01-01
- HTML5 画布调整为父级 2022-01-01
- CORS:当凭据标志为真时,无法在 Access-Control-Allow-Origin 中使用通配符 2022-01-01
- 即使每次插入第一个输入的值不同,第二个输入仍显示相同的输入值 2022-01-01
- 最佳动态 JavaScript/JQuery 网格 2022-01-01
