Does google analytics keep custom dimensions value over time? - google-analytics

Does a "user scope" dimension will keep track on the changed to the dimension value?
Will it remember the value that was set to the dimension on a past period even if it was already being updated?
Will the dimension value it always correlated to the report time period or that it is being overwrite every update?

To back up DalmTo's comment with some evidence I did the science and built a very small test page:
<html>
<head>
<title>Test</title>
<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-XXXXXX-XX', 'auto');
var d = new Date();
var currentTime = d.toLocaleTimeString();
var dimensionValue = 'I am userscope' + d + " - " + currentTime;
ga('set', 'dimension1', dimensionValue);
var dimensionValue = 'I am sessionscope' + d + " - " + currentTime;
ga('set', 'dimension2', dimensionValue);
var dimensionValue = 'I am hitscope' + d + " - " + currentTime;
ga('set', 'dimension3', dimensionValue);
ga('send', 'pageview');
</script>
</head>
<body>
</body>
</html>
So this sends a stupid message plus the datetime as dimension value.
The purpose of the test case was to make sure that nobody but me accesses the site and that all calls come from the same client id/user (albeit in multiple sessions). As an added benefit with just a few hits processing time in GA is just a few minutes, so I got to see the results quickly.
I called this a few times around 12 o'clock and then again a few minutes ago.
Results:
hit scoped custom dimensions are set per hit (no suprise here)
session scoped dimensions get the last value in the session (dito)
user scoped dimensions get the last value in the session. But they are assigned per session, not per user.
Potentially relevent screenshot:
These are two sessions for the same user which nonetheless show two different values for a user scoped custom dimension. So it's like Daimto said, only now you have a test case you can reproduce and do not need to rely on anyone's experience :-)
Of course that means you should take care yourself not to set user scoped dimensions more than once per user (else you might get inconsistencies in your segments).
(For completeness sake this would probably need to be repeated in a UserId view with session stitching enabled, but I doubt that it'll make much of a difference).

Related

Sudden increase in pageviews on google analytics?

As you can see the pages per session almost dupplicated overnight. Doesn't make sense to me so I investigated and GA only tracks one page once. I refresh the website and only one event is sent to GA. I move around and only 1 event per page is sent.
At the moment on a new page refresh it loads:
https://www.google-analytics.com/analytics.js (from service worker)
https://www.googletagmanager.com/gtag/js
https://www.google-analytics.com/analytics.js
https://www.google-analytics.com/r/collect....
https://www.google.com/ads/ga-audiences...
https://www.google.co.jp/ads/ga-audiences...
What do you think it might be?
Average time on page also decreased... but average session duration increased
The only thing that happen at that time, were those 2 peaks. Since then things got messed up for some reason. Also the website has been rebuild in at some time after the 2 peaks and I don't see any differences. Maybe the previous tracking thing was not working properly?
Any other explanations?
Code for GA:
window.dataLayer = window.dataLayer || []
window.gtag = function() {
window.dataLayer && window.dataLayer.push(arguments)
}
window.gtag('js', new Date())
const trackingId = config.trackingId
window.gtag('config', trackingId, {
send_page_view: false,
})
loadScript(`https://www.googletagmanager.com/gtag/js`)
loadScript(`https://www.google-analytics.com/analytics.js`)
Tracking with:
window.gtag('config', trackingId, {
'page_title': '...',
'page_path': '...',
})
Bounce also decreased to around 60%.

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 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
});

Google Analytics: Change userID at runtime in a SPA

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.

Resources