Reputation: 1121
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?
Upvotes: 1
Views: 1219
Reputation: 148
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 = a[i].get('trackingId');
console.log(tracking_id);
}
Upvotes: 1
Reputation: 410
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).
Upvotes: 3
Reputation: 169
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.
Upvotes: 0