Google Analytics: Change userID at runtime in a SPA - google-analytics

The documentation indicates that the userId must be set this way:
ga('create', 'UA-XXXX-Y', { 'userId': 'USER_ID' });
But in a Single Page Application (SPA), the user starts as anonymous and then logs in. So the app will start with:
ga('create', 'UA-XXXX-Y', 'auto');
And when he logs in, then I would like to change to a specific ID for tracking that user, but when I try:
ga('create', 'UA-XXXX-Y', { 'userId': 'USER_ID' });
Nothing happens, the user ID does not appears in subsequent requests.
Which is the right way of setting the userId at runtime?
Thanks.

Unfortunately, the documentation is currently incorrect. It is possible to set the user ID outside of the create method.
The reason your example isn't working is because you're calling create twice. What you want to do is call set. Here's how:
// Create the tracker instance.
ga('create', 'UA-XXXX-Y', 'auto');
// Once you know the user ID, set it on the current tracker.
ga('set', { userId: USER_ID });
Now all subsequent hits sent to GA will be associated with this user ID.
UPDATE:
The user ID documentation now reflects that it can be set outside of the create method.

Related

Google Analytics - Match UserID with my site's account ID

Each of my registered clients have an unique account ID (eg: agent n°: 00173393).
I want to retrieve this information through google analytics... It's not a personal information and for statistics use only.
I implemented userID, but how to match userID and the accounts IDs ?
Is it possible to create a variable for the account ID number ?
Why don't you use the account ID as User ID as well? That way you would have a 1-to-1 match:
ga('create', 'UA-XXXXX-Y', 'auto', {
userId: accountId
});
Please note however that the User ID is not exposed back by Google Analytics. If you want to retrieve it, you need to save it inside a custom dimension:
Admin -> Property -> Custom Dimensions -> Create one with User scope
Add custom dimension tracking to your code
For instance:
ga('create', 'UA-XXXXX-Y', 'auto', {
userId: accountId,
});
ga('set', 'cd1', accountId); // if it's custom dimension n1
ga('send', 'pageview');
Then you can retrieve the User ID via the UI:
or the API

Google analytics - event hits don't work after sendHitTask

Just started integration of Salesforce Community with Universal Google Analytics (beginner in both).
Adding GA integration code in tag.
Downloaded GA debugger for Chrome.
Browser: Chrome.
Here is code in the tag:
<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_debug.js','ga');
window.ga_debug = {trace: true};
ga('create', 'UA-xxxxxxxxx-x', 'auto');
ga('send', 'pageview');
ga(function(tracker) {
tracker.set('sendHitTask', function(model) {
var hitPayload = model.get ( 'hitPayload' );
console.log ( 'models payload: ' + hitPayload );
// need this section to get user id value to send to dimension
//ga('set', 'dimension3', tracker.get('userId'));
});
});
</script>
Later in the code we make calls to track events.
After I've added
"ga(function(tracker) {" code section
those calls to track events do Not work any more (used to work).
What is wrong with the code above?
When you set the sendHitTask for the tracker, you're overriding it; that is, you're removing the normal task that sends data to Google Analytics and replacing it with your own. So, after you do this, any hits you track won't be sent to GA.
Instead, before you set the sendHitTask, you need to get the existing one and execute that function first in your new sendHitTask function.
From documentation for adding to a task, some code to do this follows. Before your tracker.set call, you need to add:
// Grab a reference to the default sendHitTask function.
var originalSendHitTask = tracker.get('sendHitTask');
Then, in your function that you're assigning to sendHitTask, you'll need to call that function:
// Send the normal request to Google Analytics
originalSendHitTask(model);
You have crippled your sendHitTask, because the method you provided to override it does not do any sending - you have replaced it with a function that logs something to the console and nothing else.
If you look at the example in the documentation you see that there they stored the original sendHitTask in a variable and called within the custom function.
Also you cannot use the ga object within the task, you access the properties of your tracker via the model that is passed in to the task.
So you would need something like
ga(function(tracker) {
// Grab a reference to the default sendHitTask function.
var originalSendHitTask = tracker.get('sendHitTask');
tracker.set('sendHitTask', function(model) {
model.set('dimension3',model.get('userId'));
originalSendHitTask(model);
});
});
Also you might consider to use the customTask to add custom behavior, although it will give the same result.

ClientId not getting captured

We have three custom dimensions defined in Google Analytics:
ClientId (dimension1): Session-scoped
SessionId (dimension2): Session-scoped
Hit Timestamp (dimension3): Hit-scoped
And these are being fed from an on-page script:
$(document).ready(function() {
(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');
function getClientId() {
try {
var trackers = ga.getAll();
var i, len;
for (i= 0, len = trackers.length; i < len; i += 1) {
if (trackers[i].get('trackingId') === 'UA-XXXXXXXX-1') {
return trackers[i].get('clientId');
}
}
}
catch(e){
//do nothing
}
return 'false';
}
function getSessionId() {
return new Date().getTime() + '.' + Math.random().toString(36).substring(5);
}
function getTimeStamp() {
return new Date().getTime();
}
ga('create', 'UA-XXXXXXXX-1', 'auto');
ga('require', 'displayfeatures');
ga('require', 'linkid', 'linkid.js');
var clientId = getClientId();
var sessionId = getSessionId();
var timeStamp = getTimeStamp();
ga('send', 'pageview', {
'dimension1' : clientId,
'dimension2' : sessionId,
'dimension3' : timeStamp
});
});
</script>
Now, the marketing team tells us that ClientId is not getting captured. They shared data where we had some 24,000 rows, out of which only two had valid client ids. By contrast, Session ID and Hit Timestamp are being captured perfectly.
When I do a quick check on the website (by assigning the code for getClientId() to another temporary function and calling it), I get the ClientId.
I'm really not sure what's causing this to be missed on the live website. Can someone point out something that might be awry?
You should consider loading the GA library as recommended in the <head> section of your site rather than on $(document).ready. This is so that the analytics tracking has the soonest possibility to start tracking user engagements. In addition, if you load the analytics after DOM is ready or after the page has completely loaded, then there is the chance you miss some metrics if, for example, a user lands on your page, and then navigates away before the analytics library has a chance to capture their data.

How to check ga dimensions(Google Analytics)?

As per my code I am setting the 'dimension1' field.
Defined fields: email(contains user email)
ga('set', 'dimension1', email);
ga('send', 'pageview');
How to see the dimension1 values in GA?
Original requirement: Track id of each user.

How to get statistics of where visitors come from via URL params

There are many QR codes that contains URL of website such as:(it just demos link)
http://www.popupstore.com/index.php?qrcode_type=magazine&location=Singapore
http://www.popupstore.com/index.php?qrcode_type=banner&location=Vietnam
I need a way can summary to know that where customer come from (nearly same as source/channel in Google Analytics):
Type: Mazazine, banner, etc.
Location: Vietnam, Singapore, etc.
Can anyone help me please :)
You could create two Custom Dimensions, each for Type and another for Country
As per your need define the appropriate Scope of the dimension, a Hit level or Session level scope would be appropriate.
You need to push custom dimensions into Google Analytics i.e. additonal JS code in your site.
ga('send', 'pageview', {
'dimension1': 'Magzine',
'dimension2': 'Singapore'
});
How this works
User scans the code and visits the store
Site has a JS code snippet that would get the query parameters from the URL and sets a custom dimension for each parameter
Setting the custom dimension would let Google Analytics know the value of the Type and Country
It is your JS code that tells Google Analytics what value to take for custom dimension. Google Analytics would not know that the value came from the URL.
To get a query parameter value via javascript you can refer to this answer, If you take the function provided there by Jan Turon (head over and give him an upvote of this helps you):
function getJsonFromUrl() {
var query = location.search.substr(1);
var result = {};
query.split("&").forEach(function(part) {
var item = part.split("=");
result[item[0]] = decodeURIComponent(item[1]);
});
return result;
}
You can use this to dynamically set the dimensions based on the url. You first call the function to return an JSON object that has the key/value pairs from the query parameters, then you insert the needed values to set the dimensions:
result = getJsonFromUrl();
ga('send', 'pageview', {
'dimension1': result.qrcode_type,
'dimension2': result.location
});

Resources