Google analytics in a cordova web-app

We use Google Analytics in most of the websites we build. With our apps we have more options.

But when you try to add google analytics to your Cordova web-application you will find that it doesn’t work out of the box.

Because your application is running from file:// google analytics won’t work. You need to pull three small tricks to make it work.

  1. Change the url in the analytics.js file. Add http: in front of the double //. Else it would try to find the analytics.js file on file://www.google-analytics.com. The other option would be to serve the file yourself.
  2. In the “ga” “create” add “storage: none” because you cannot store cookies on the file:// protocol.
  3. Add “ga set checkProtocolTask” disables the script checking if we are working on the file:// protocol. Setting the location of the dataObject makes sure google registers your hit.

//code you get from google analytics add 'https:' before the //

(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-x', {

	'storage': 'none', //add this part to prevent

	'clientId': device.uuid

});



ga('set', 'checkProtocolTask', function(data) {

	data.set('location', 'https://www.yourUrl.com');

});