简体   繁体   中英

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. Is this possible? Is there some sort of function I can call in javascript, which returns the 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?

No matter how GA is implemented (via GTM or hardcoded) you can simply get tracking ID via:

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

If there're more than 1 GA on page you can access them too (just iterate throuh array).

An updated version of @Jacek Szymanski's post.

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.

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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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