Get Google Analytics ID using Javascript

I am trying to extract google analytics id from 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 I am getting this error:

TypeError: 'null' is not an object (Evaluate 'Document.getElementById (' scripttag '). Value')

Any ideas?

+3


source to share


3 answers


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



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

      

+6


source


In April 2017 this works:



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

+1


source


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

      

If you already have a tracker, you can get it using

tracker.get('trackingId')

      

Carefull , don't forget the best Google Analytics recommendations

Do not use ga object methods outside of readyCallback, as methods may not yet be available.

0


source







All Articles