Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Durandal Google Analtyics Tracking

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?

like image 504
Drew Freyling Avatar asked Jun 05 '13 23:06

Drew Freyling


2 Answers

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.

like image 54
gerrod Avatar answered Nov 01 '22 05:11

gerrod


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]);
});
like image 20
Kyeotic Avatar answered Nov 01 '22 06:11

Kyeotic