Chris J Allen
Chris J Allen

Reputation: 19207

Reliably fetching the Google Analytics Tracking ID from another script

I need to retrieve the Google Analytics Tracking ID via JavaScript for use in another script. Something like:

var ga_id = (typeof ga !== 'undefined') ? ga.getAll()[0].get('trackingId') : 'Unable to retrieve GA id'

My Analytics is loaded using Tag manager, so even though I'm running my own JavaScript quite late in the page, its not detecting the presence of the ga object. ( I can access it without a problem via the developer tools console.)

How can I ensure that ga has loaded before trying to access its properties?

Upvotes: 1

Views: 161

Answers (1)

BNazaruk
BNazaruk

Reputation: 8081

It's there on window loaded and you can see it in the GTM preview like so:

enter image description here

I have this CJS in that var (used your code):

enter image description here

Although this is ample in my case, yours may differ, so what you can do is the following:

  1. Make a custom html tag that runs on pageload and deploys a closure with a timeout in it.
  2. In the timeout callback push a dataLayer event.
  3. Now move the tag that you want to get the value of the property id for to the dataLayer event trigger (custom event).

This is not very elegant, but it'll work. Again, for normal implementations, Window Loaded should be ample.

Upvotes: 1

Related Questions