Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get Google Analytics ID with Javascript

Tags:

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?

like image 757
Alosyius Avatar asked Jan 15 '23 06:01

Alosyius


2 Answers

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

var accountId = _gaq._getAsyncTracker()._getAccount();
like image 151
Will Hawker Avatar answered Jan 16 '23 19:01

Will Hawker


In April 2017, this works:

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

like image 28
Daniel Avatar answered Jan 16 '23 19:01

Daniel