Reputation: 1
Recently we upgraded to universal analytics which appears to all be working. I have been trying to capture the clientID to a js variable via the following code:
<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','//www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-REMOVED', 'xxxx.xxx');
ga('require', 'linkid', 'linkid.js');
ga('send', 'pageview');
ga(function(tracker) {
var clientId = tracker.get('clientId');
});
</script>
To prove the variable clientID is being captured I try and write it to the page using the following code:
<script>
document.write(clientId);
</script>
Which writes nothing to the page.
I have browsed this site and others but can not figure what i am missing. I feel like i'm overlooking something blindingly obvious. Any help much appreciated.
Ultimately i will be writing the variable to a form field to process offline steps occuring in a 3rd party system.
Upvotes: 0
Views: 863
Reputation: 21
In your code, the variable clientId is declared inside a function. Hence, 'clientId' does not have a global scope. Its value is not accessible outside of the function. Need to assign the value from tracker.get('clientId')
to a global variable if you need to use it later. See http://learn.jquery.com/javascript-101/scope/
Upvotes: 2
Reputation: 2383
Calling the following does work on my page: ga(function(tracker) { alert(tracker.get('clientId'));})
I am doing exactly the same thing as you but instead of writing it to a page, I am alerting it. Maybe document.write
is not working for you as expected?
If the code you posted is same as the one you are using, The reason it is not working is because document.write
runs before the callback is called. remember that everything that you pass into ga()
is asynchronous.
Upvotes: 0