简体   繁体   English

如何获取基于Google跟踪代码管理器的Google Analytics(分析)跟踪ID?

[英]How can I acquire the Google Analytics Tracking ID based on the Google Tag Manager?

I want to retrieve the Google Analytics Tracking ID based on the Google Tag Manager ID, via code. 我想通过代码基于Google跟踪代码管理器ID检索Google Analytics(分析)跟踪ID。 Is this possible? 这可能吗? Is there some sort of function I can call in javascript, which returns the ID? 我可以在javascript中调用某种返回ID的函数吗? The Tag Assistant extension for Chrome correctly sees the Analytics UA code, with only the Tag Manager scripts, so it should be doable I guess? Chrome的Tag Assistant扩展程序仅使用Tag Manager脚本即可正确看到Analytics UA代码,因此我猜应该可行吗?

No matter how GA is implemented (via GTM or hardcoded) you can simply get tracking ID via: 无论如何实施GA(通过GTM或硬编码),您都可以通过以下方式简单地获取跟踪ID:

ga.getAll()[0].get('trackingId');

If there're more than 1 GA on page you can access them too (just iterate throuh array). 如果页面上有1个以上的GA,您也可以访问它们(只需遍历数组即可)。

An updated version of @Jacek Szymanski's post. @Jacek Szymanski的帖子的更新版本。

Since there can be multiple instances of the Google Analytics tag present on the page I would recommend you to iterate the whole "ga.getAll()" array. 由于页面上可能存在Google Analytics(分析)标记的多个实例,因此建议您迭代整个“ ga.getAll()”数组。

var a = ga.getAll();
for(var i = 0; i < a.length; i++){
    var tracking_id = ga.getAll()[i].get('trackingId');
    console.log(tracking_id);
}

In the Google Tag Assistant, you can choose the tab "Code Snippet" to see where it is grabbing your GA Tracking ID from your page. 在Google Tag Assistant中,您可以选择“代码段”标签,以查看它从页面中获取GA跟踪ID的位置。 You should see that it is taking it from the code snippet you placed on your site in order to enable tracking. 您应该看到它是从放置在您站点上的代码片段中提取出来的,以便启用跟踪。

You can use something like document.evaluate('{{Xpath}}', document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue to retrieve that code snippet and manipulate it to retrieve your tracking code in JS. 您可以使用诸如document.evaluate('{{Xpath}}', document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue来检索该代码段,并对其进行操作以在JS中检索您的跟踪代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM