Migrate Google Analytics storage from cookies to local storage - google-analytics

Before we knew about the different storage options for Google Analytics (analytics.js) we launched our site and used the default, cookie-based, tracking. We now want to switch to storing the client id using localStorage, so that we don't have to send the cookies to the server for each request.
Is it possible to migrate users who have the cookie set, so that not every session will show up as a new brand new user?

It's certainly possible, the trick is to let the Google Analytics script extract the client id from the cookie for you when you can't find an id stored in local storage.
/* Google Analytics initialization code */
(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')
/* Fallback to cookies if the browser doesn't support localStorage */
if (!window.localStorage) {
ga('create', 'UA-XXXXX-Y', 'auto')
}
/* If we are already using localStorage, continue with that */
else if (localStorage.getItem('gaClientId')) {
ga('create', 'UA-XXXXX-Y', { storage: 'none', clientId: localStorage.getItem('gaClientId') })
}
/* Migrate users from cookies to localStorage */
else if (document.cookies.indexOf('_ga') !== -1) {
ga('create', 'UA-XXXXX-Y', { cookieExpires: 1 })
ga(function (tracker) { localStorage.setItem('gaClientId', tracker.get('clientId')) })
}
/* Setup a fresh user */
else {
ga('create', 'UA-XXXXX-Y', { storage: 'none' })
ga(function (tracker) { localStorage.setItem('gaClientId', tracker.get('clientId')) })
}
ga('send', 'pageview')
After the previous cookie timeout (defaults to 2 years if not specified), it should be safe to remove the cookie-migration part. The script would then look something like this:
/* Google Analytics initialization code */
(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')
/* Fallback to cookies if the browser doesn't support localStorage */
if (!window.localStorage) {
ga('create', 'UA-XXXXX-Y', 'auto')
}
/* Store Google Analytics client ID in localStorage */
else {
ga('create', 'UA-XXXXX-Y', { storage: 'none', clientId: localStorage.getItem('gaClientId') })
ga(function (tracker) { localStorage.setItem('gaClientId', tracker.get('clientId')) })
}
ga('send', 'pageview')

Related

Google Goal conversion not working when I download pdf

Google Goal conversion not working when I download pdf.
Here I followed following steps:
<html>
<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-XXXXXX', 'auto');
ga('send', 'pageview');
</script>
<a href="/wp-content/uploads/2017/03/SEO-ebook-Final.pdf" onClick="javascript:_gaq.push(['_trackPageview','/wp-content/uploads/2017/03/SEO-ebook-Final.pdf']);">Ok<a/ class='bold-uppercase'>
</html>
gaq.push us classic Google analytics code as in ga.js. Your Google Analytics snippet shows you are using analytics.js which is universal analytics.
So basically you are mixing things you shouldn't be.
<script>
/**
* Function that tracks a click on an outbound link in Analytics.
* This function takes a valid URL string as an argument, and uses that URL string
* as the event label. Setting the transport method to 'beacon' lets the hit be sent
* using 'navigator.sendBeacon' in browser that support it.
*/
var trackOutboundLink = function(url) {
ga('send', 'event', 'outbound', 'click', url, {
'transport': 'beacon',
'hitCallback': function(){document.location = url;}
});
}
</script>
You'll also need to add (or modify) the onclick attribute to your links. Use this example as a model for your own links:
Check out example.com
code ripped from Track outbound links

Google Analytics Opt-out

To be OK with the nonsense cookie law of the Grosse European Komission, I've built this little script to opt-out the GA tracking code. The result is a popup asking once in the session for OK vs CANCEL GA. What do you think of it?
(function() {
var message = "GOOGLE ANALYTICS COOKIE\nCookie or not cookie, that is the question\n\nI opt for Google Analytics pageview anonymous tracking.\n\nJe consens au suivi d'audience anonyme Google Analytics.";
if (!sessionStorage['key_name']) {
if (confirm(message) == true) {
sessionStorage.setItem('key_name', 'gaOK');
}
else {
sessionStorage.setItem('key_name', 'gaOut');
}
}
if (sessionStorage['key_name'] == 'gaOK') {
(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-XXXXXXXX-N', 'auto');
ga('send', 'pageview');
}
})();

Polymer - Track app usage with Google Analytics

I'm trying to use Google Analytics (web) with my polymer app (updating the tracker object in routing.html as per this GA SPA doc). I used the Polymer Starter Kit as a starting point. I'm not seeing any pageviews though, apart from / - what's the suggested way of tracking app usage?
routing.html
page('/topstories', function () {
app.route = 'topstories';
window.ga('set', 'page', '/topstories');
});
page('/about', function () {
app.route = 'about';
window.ga('set', 'page', '/about');
});
index.html
<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-xxxxxxxxx-1', 'auto');
ga('send', 'pageview');
</script>
In addition to setting the page value on the tracker, you also have to send the pageview hit to Google Analytics. In your route callback functions you'll need to add the line:
ga('send', 'pageview');
You could also write a function that does all this for you, so you don't have to repeat the set and send calls every time.
function updatePage(path) {
return function() {
app.route = path.slice(1);
ga('set', 'page', path);
ga('send', 'pageview');
}
}
The your page route declarations would look like this:
page('/topstories', updatePage('/topstories'));
page('/about', updatePage('/about'));
My solution takes advantage of the middleware-ish page.js handler:
// Routes
page('*', scrollToTop, closeDrawer, function(ctx, next) {
ga('set', 'page', ctx.path); // simply add
ga('send', 'pageview'); // these rows
next();
});
But this also fires as the / route is initialised, so to not double count visits, remove the final ga('send', 'pageview'); from your <script> block.

why is google universal analytics not working in my webapp?

I'm using GA in my webapp without a plugin. I'm just adding the analytics.js and changing a few bits i think are required for it to work inside a webapp (no cookies, file:// urls, etc). I'm following the technique described here http://www.blastam.com/blog/index.php/2013/07/ga-universal-analytics-phonegap-mobile-apps - it seems to be in line with the analytics documentation.
I have a web emulator of the app too, where i dont do these changes. In the web emulator, I can see requests going out where I call them. In the app, nothing happens - no errors, no requests.
// google analytics
(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','http://www.google-analytics.com/analytics.js','ga');
ga('create', this.settings.gatrackerid, 'auto');
if (!this.settings.emulate) {
// the app version
ga('set', {
'appName' : this.settings.appname,
'appId' : this.settings.appid,
'appVersion' : this.settings.version,
'checkProtocolTask' : null, // allow file://urls
'storage' : 'none', // no cookies available
'clientId' : device.uuid // well use phonegaps uuid
});
} else {
// the web version
ga('set', {
'appName' : this.settings.appname,
'appId' : 'emulate '+this.settings.appid,
'appVersion' : this.settings.version
});
}
ga('send', 'screenview',{
'screenName' : 'foo' // works on web, not in app
});
Anybody any idea on whats going wrong and how to debug it ?
I was reading the blastam post wrong. The storage and client id are supposed to replace the third parameter of the create statement, the cookie info. The code to create a tracker is
ga('create', trackerid, cookieinfo)
In my code, cookieinfo was set to 'auto'. Works on the web, not in the app. The right code is
if (!this.settings.emulate) {
ga('create', this.settings.gatrackerid, {
'storage' : 'none',
'clientId' : device.uuid
});
ga('set', {
'appName' : this.settings.appname,
'appId' : this.settings.appid,
'appVersion' : this.settings.version,
'checkProtocolTask' : null
});
} else {
ga('create', this.settings.gatrackerid, 'auto');
ga('set', {
'appName' : this.settings.appname,
'appId' : 'emulate '+this.settings.appid,
'appVersion' : this.settings.version
});
}
and that works just great, no plugins required.

Load Google Analytics from tampermonkey

I'm trying to place Google Analytics code inside a Tampermonkey userscript, however the code simply doesn't work as evidenced by:
The callback function for the pageview doesn't fire and
I don't show up as an "active user on site" in Real-Time view for Google Analytics
Here is the script, nice and simple (some values obfuscated):
// ==UserScript==
// #name GA Injector
// #namespace mynamespace
// #version 0.1
// #description Injects google analytic code for testing
// #match mywebpage
// #copyright 2014 me
// #require http://code.jquery.com/jquery-latest.js
// ==/UserScript==
Console.log('This part works okay');
(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', 'mytrackingcodeishere', 'auto');
ga('send', 'pageview', {
'hitCallback': function() {
console.log('Tracking worked okay!');
}
});
The script works fine when run in Chrome's javascript console, what is it about Tampermonkey or my configuration that prevents Google Analytics from being run?
Try simply injecting this entire code into the page scope, like this:
var script = document.createElement('script');
script.innerHTML = "..Your JS Code..";
document.body.appendChild(script);
If it does works when run from console, it will this way.

Resources