Created
February 15, 2017 10:03
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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