Alosyius
Alosyius

Reputation: 9151

Get Google Analytics ID with Javascript

I am trying to extract the Google analytics ID from a html document.

I found the following function:

function get_UA() {

txt = document.getElementById('scripttag').value;

var matches = txt.match(/(UA-[\d-]+)/);

if (matches[1]) {

    alert(matches[1]);

}

}

But im getting this error:

TypeError: 'null' is not an object (evaluating 'document.getElementById('scripttag').value')

Any ideas?

Upvotes: 4

Views: 5507

Answers (3)

oxmolol
oxmolol

Reputation: 125

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

if you already have a tracker you can obtain it with

tracker.get('trackingId')

Carefull, Dont forget google analytics best practices

Don't use ga object methods outside a readyCallback as the methods may not be available yet.

Upvotes: 2

Daniel
Daniel

Reputation: 4321

In April 2017, this works:

ga.getAll()[0].b.data.values[':trackingId']

Upvotes: 2

Will Hawker
Will Hawker

Reputation: 733

Can you access the _gaq variable? If you can, and the page is using asynchronous tracking...

var accountId = _gaq._getAsyncTracker()._getAccount();

Upvotes: 6

Related Questions