0

I'm planning to use Google Analytics Measurement Protocol. I'm currently planning to capture the Client ID (cid) by including it as a URL parameter on some Ajax requests.

I've found that I can expose the Client ID value like this:

var ga_cid;
ga(function(tracker) {
    ga_cid = tracker.get('clientId');
});

I'm concerned that this route is poor form as it's polluting the global namespace. However, I've been unable to unearth a more elegant (best practice) solution.

What is the "right" way? Am I overthinking this?

Sonny
  • 8,204
  • 7
  • 63
  • 134

2 Answers2

0

Yes you may be right on this. Its instead better not to get the Client ID from the Cookie as the official documentation recommends. You can do something like below:

ga(function(tracker) {
  var clientId = tracker.get('clientId');
});

There are more options mentioned on this page on how to retrieve it based on how your page is setup.

Sonny
  • 8,204
  • 7
  • 63
  • 134
pal4life
  • 3,210
  • 5
  • 36
  • 57
  • The code you've supplied is the one from their documentation. It does not make the Client ID available for use, hence my post. – Sonny Mar 03 '17 at 20:00
  • No there is a huge difference between the two codes actually. If you declare var outside the function you are increasing it to global scope. As long as declare the variable within the function, you can keep the scope as local. http://stackoverflow.com/questions/500431/what-is-the-scope-of-variables-in-javascript – pal4life Mar 03 '17 at 20:07
  • You're misunderstanding me. I know the value scope is local in the example you've given. It is the example from the official documentation. Having it local there doesn't give me the ability to access the value elsewhere in my JavaScript, like when making an Ajax call, as I discussed. That is why I presented my modified version, with the question of whether that was the way to accomplish it, or there was a better route. – Sonny Mar 03 '17 at 20:17
0

I ended up making a cookie and referencing it from PHP instead of a global JavaScript variable that I'd have to pass when making AJAX calls.

// put the Google Analytics Client ID into a cookie, so that it will be available to PHP
ga(function(tracker) {
    var date = new Date();
    date.setTime(date.getTime() + (30 * 24 * 60 * 60 * 1000));
    document.cookie = 'ga_cid=' + tracker.get('clientId') + '; expires=' + date.toUTCString() + '; path=/';
});

Then in PHP:

$ga_cid = filter_input(INPUT_COOKIE, 'ga_cid');
Sonny
  • 8,204
  • 7
  • 63
  • 134