从我看来,谷歌似乎正在逐步淘汰analytics.js,取而代之的是他们的标签管理器。
如何为多个分析账户启动google analytics新的gtag跟踪代码?
如下所示:
<script async src="https://www.googletagmanager.com/gtag/js?id=UA-108285779-2"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'UA-108285779-2');
gtag('config', 'ANOTHER CODE');
gtag('config', 'ANOTHER CODE');
</script>发布于 2021-03-08 21:08:15
简写:
是,您可以多次添加相同类型的产品,方法是为您拥有的每个相应的Google帐户+属性ID调用
gtag('config', ...)。
详情:
时间是2021年,我也有同样的问题,但我太偏执了,不相信这个帖子投票最多的答案,因为它描述了一种与我自己在测试如何工作时不同的体验。然而,首先,为了在2021年回答OP的问题,我们必须查看谷歌官方文档中的two条目,因为这两个条目都没有完全回答这个问题,但当它们结合在一起时,可以让我们对如何解决这个问题更有信心:
我使用<e232回答产品添加多个相同类型的应答:是。)
下面是我如何使用JavaScript完成OP场景的示例片段。如果您在浏览器的控制台中尝试这样做,您应该会看到为您在下面代码片段的googleIds数组中设置的每个ID添加了一个惟一的脚本。
备注:
googleIds数组包含五个is。<script>标记设置为页面,但代码段本身仅显式构建并将其中一个标记设置为.
// An array of IDs I want to load on the same page(s) at the same time
var googleIds = ["AW-00000000", "AW-00000001", "AW-00000002", "DC-00000000", "UA-00000000-1"];
// Setting dataLayer & gtag to window because I'm using a custom code text field in a tag management system
window.dataLayer = window.dataLayer || [];
window.gtag =
window.gtag ||
function() {
window.dataLayer.push(arguments);
};
window.gtag("js", new Date());
// Flag used to ensure script only set with first ID, and rest of IDs are pushed to dataLayer
var gtagScriptExists = false;
// ID validation regex. Only tested with AW-*, but DC & UA are also valid prefixes
var validIdStructure = new RegExp(/(AW|DC|UA)-[0-9]{8,}(-[0-9]{1,})?/);
// Push IDs into dataLayer and set initial gtag/js?id= script to page using first ID in googleIds array
for (var i = 0; i < googleIds.length; i++) {
var gtagId = googleIds[i];
// Validate that the ID being passed isn't a big weirdo
var idIsValid =
typeof gtagId === "string" && gtagId.match(validIdStructure);
if (idIsValid) {
window.gtag("config", gtagId);
// NOTE: gtag script only needs to be set to page once, but each gtag('config', <ID>) that's pushed to the dataLayer will add subsequent gtag/js?id=<ID> scripts to the page
if (!gtagScriptExists) {
// Set initial gtag/js?id=<first ID> script to <head>
var script = document.createElement("script");
script.type = "text/javascript";
script.async = true;
script.src = "//www.googletagmanager.com/gtag/js?id=" + gtagId;
document.getElementsByTagName("head")[0].appendChild(script);
// Update gtag/js?id= script status flag so this initialization script is only set for the first ID, and not all the IDs in the array
gtagScriptExists = true;
}
}
}
发布于 2019-12-01 18:56:28
是的,根据文档,这是正确的。但是它没有为我生成关于后续代码的数据,直到我添加了
<script async src="https://www.googletagmanager.com/gtag/js?id=ANOTHER_CODE"></script>在代码块的正上方。要么是我偶然发现了一个可以正常工作的杂碎软件,要么是谷歌需要更新他们的文档。
发布于 2019-03-28 02:45:28
这似乎是官方的做法,according to the documentation。
https://stackoverflow.com/questions/46789189
复制相似问题