I'm using Durandal 1.2 and the Durandal Router Plugin and wanting to track page views in the SPA through Google Analytics:
window._gaq.push(['_trackPageview', location.pathname + location.search + location.hash]
I know I could listen for the hashchange event or even hook into via Sammy. I'd rather not do that given Durandal is currently being rewritten to remove the dependency on Sammy.
My question is, is there a way to set this up using the Durandal Router Plugin?
Have a look at onNavigationComplete
in the router. You could override that to do your analytics:
// Store reference to router's onNavigationComplete so you can call it
var onNavigationComplete = router.onNavigationComplete;
router.onNavigationComplete = function (routeInfo, params, module) {
// Run the default onNavigationComplete
onNavigationComplete.call(this, routeInfo, params, module);
// Analytics!
window._gaq.push(['_trackPageview', location.pathname + location.search + location.hash]
};
Obviously you'll need to do this somewhere very early in your application's lifecycle, such as in your main.js
.
You could also attach to the navigation complete
event, so that you don't have to store the router's original function.
//Update anaytics whenever the router navigates
router.on('router:navigation:complete', function(instance, instruction) {
window._gaq.push(['_trackPageview', instruction.fragment]);
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With