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
.