Blog

Google analytics in a cordova web-app

By:
on:

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

However, 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 //. Otherwise, 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');

});

KOEN IS HAPPY TO INTRODUCE APPSALOON
APPSALOON BV
Bampslaan 21 box 3.01
3500 Hasselt
Belgium
VAT: BE08 4029 5063
2021 © AppSaloon All Rights Reserved
linkedin facebook pinterest youtube rss twitter instagram facebook-blank rss-blank linkedin-blank pinterest youtube twitter instagram