Originally we were using the popular Cordova Google Analytics Plugin. There are advantages to using the plugin, as it interfaces with the native GA SDKs and provides features such as request batching and offline tracking, but we ran into regular issues and a consistently broken Android build. For our simple event tracking and pageview use cases we decided to go with a more straightforward approach and use the analytics.js file directly.
The tracking worked fine when serving Ionic in the browser but did not work on any device, even though the hitCallback was being successfully invoked. (It turns out the hitCallback gets invoked on any response from the server so do not rely on it as an indicator of a successful ‘hit’.)
The problem turned out to be that GA was checking to see whether the current browser protocol was http://
or https://
so it could match it. In an Ionic app the protocol is actually file://
so this needed to be circumvented.
// Disable checkProtocolTask.
ga('set', 'checkProtocolTask', null);
// Set the transport url manually.
ga('set', 'transportUrl', 'https://www.google-analytics.com/collect');
Another issue is that Android 5.0+ doesn’t support third party cookies by default, so you should use localStorage (more info) for persisting the clientId
.
So with all that, the entire process becomes:
// Sets window.ga
require('./analytics.js');
ga('create', {
// Disables cookies.
storage: 'none',
// Your GA tracking id.
trackingId: 'UA-12345678-1',
// Will return null if not set, and GA will then assign one.
clientId: localStorage.getItem('ga:clientId')
});
ga('set', 'checkProtocolTask', null);
ga('set', 'transportUrl', 'https://www.google-analytics.com/collect');
ga(function(tracker) {
if ( !localStorage.getItem('ga:clientId') ) {
// Save the assigned id for the next time the app boots.
localStorage.setItem( 'ga:clientId', tracker.get('clientId') );
}
});
Then…
ga('send', 'pageview', 'homepage');
ga('send', 'event', 'category', 'action', 'label', 1);
I also like to add ga
to the $rootScope
so it can be called within your templates also:
$rootScope.ga = $window.ga;
<button ng-click="$root.ga('send', 'event', 'buttonClick')"></button>
If you run into any issues, be sure to substitute analytics.js
for analytics_debug.js
which provides excellent logs for each action that GA takes.
More information about ga('set', ...)
and ga('get', ...)
can be found here.
And lastly don’t forget to place <access origin="https://*.google-analytics.com"/>
in your config.xml
to allow GA to make its requests!
4 Comments
Comment replies are not available offline