Mirror318
Mirror318

Reputation: 12673

Google Analytics get tracker by trackingId

I currently have this code, to try and find the right tracker I need (among 8-12 trackers):

ga.getAll().forEach(function(tracker) {
    if(tracker.get('trackingId') === "UA-62921111-4") {

Instead of getting every tracker and iterating through them, is there an easy way to do something like ga.getTracker("UA-62921111-4")?

Upvotes: 2

Views: 2314

Answers (2)

Mirror318
Mirror318

Reputation: 12673

I found this to be a good one-liner:

var tracker = ga.getAll().filter(tracker => (tracker.get('trackingId') === 'UA-62925944-4'))[0]

But note that if you have multiple trackers, ga might seem ready before the tracker you want has loaded. I was wanting to get data from the tracker for form fields, so I inserted those fields on submit, to make sure everything had loaded.

Upvotes: 0

Inus Saha
Inus Saha

Reputation: 1918

There is no ga.getTracker on analytics.js. it only has ga.getByName and ga.getAll.

for your reference you can check this. https://developers.google.com/analytics/devguides/collection/analyticsjs/accessing-trackers

So to achieve what you need i have written the following code which should be added to your file after the analytics.js has been loaded:

(function(){
    trackers = {}
    ga.getAll().forEach(function(tracker) {
        trackers[tracker.get('trackingId')]=tracker;
    });
    ga.getTracker=function(id){
        if(trackers[id])
        return trackers[id];
    };
})();

this basically fetches all the trackers once and stores them in an object and it defines the missing ga.getTracker.

so now you can call ga.getTracker("UA-62921111-4") function to get your tracker.

Upvotes: 4

Related Questions