Robbert
Robbert

Reputation: 1330

Analytics and Google Client ID get set

I am saving a Analytics client ID in a hidden field in my website by the following script:

// Assuming you are using jQuery
$(document).ready( function() {
  // Makes use of the Universal Analytics API 'ga' object
  ga(function(tracker) {
   var clientId = tracker.get('clientId');
   $("clientId").val(clientId);
 });
 });

And then send it to my server.

But sometimes a user submits the form and there is no analytics client id saved in my database.

So my question is: When does a Analytics Client ID get set?

Only If a user is logged in with Google account?

Upvotes: 0

Views: 2004

Answers (2)

Avi
Avi

Reputation: 2383

The client ID is set/generated whenever you send a hit to the GA servers. So, If you try to read the clientId after you have sent a pageview hit, you should always get a client ID.

Hope this answers your question.

You could also try something like this:

ga('create', 'UA-XXXXXXX-Y');
ga('send', 'pageview');
ga(function() {
  $(document).ready(
    // Set the field value.
  );
});

Upvotes: 1

Mark Hansen
Mark Hansen

Reputation: 1062

How frequently is this clientId not getting set? There are a couple possibilities for why it might not be set.

(1) Some users block Google Analytics. Google even provides this tool which allows them to do that.

(2) If your Javascript is running before the analytics.js library has loaded, then the tracker object may not exist yet.

My understanding is that $(document).ready does NOT guarantee that the analytics.js has loaded and created the tracker instance. That's because the tracking code script reference is dynamically injected into the page to ensure that it loads AFTER all the resources referenced in the original HTML. The issue of when Google Analytics scripts are loaded with respect to the document ready event discussed here.

Your site visitors definitely do NOT need to be logged in to Google in order to be assigned a clientId.

Upvotes: 0

Related Questions