Skip to content

Instantly share code, notes, and snippets.

@crewstyle
Created February 15, 2017 10:03
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save crewstyle/11a83ee049e8375b1f1d5555644265bb to your computer and use it in GitHub Desktop.
Save crewstyle/11a83ee049e8375b1f1d5555644265bb to your computer and use it in GitHub Desktop.
How to get a parameter's value from URL and set a client ID into GA tracker, to retrieve it later
/**
* Retrieve parameter from URL
*/
function findParameter(param) {
var result = 0, tmp = [], BreakException = {};
// Iterate on all and breaks when param is found
// @see http://stackoverflow.com/a/2641374
try {
location.search
.substr(1)
.split('&')
.forEach(function (item) {
tmp = item.split('=');
// Check parameter
if (tmp[0] !== param) {
return;
}
// Parameter found!
result = decodeURIComponent(tmp[1]);
throw BreakException;
});
} catch (e) {
if (e !== BreakException) throw e;
}
// Return parameter's value
return result;
}
// Build usefull vars
var _clientid = findParameter('_clientid'),
_ua = 'UA-XXXXXXXX-Y',
_obj = {'allowLinker': true};
// Check client ID
if (0 != _clientid) {
_obj.clientId = _clientid;
}
// Initliaze GA script
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','https://www.google-analytics.com/analytics.js','ga');
ga('create', _ua, 'auto', _obj);
ga('send','pageview');
// Instanciate clientId from tracker
var clientId = '';
ga(function (tracker) {
clientId = tracker.get('clientId');
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment