Google Analytics is a great tool to figure out what’s going inside your web application. It gives you real-time monitoring on the pages they visit, the time they spend on your site and much, much more…
Recently we switched from a standard ASP.NET MVC application to a Single Page Application. The problem is that Google Analytics has no idea when you switch pages, so you loose a lot of interesting reporting.
To fix this you can use the fact that most SPA’s use hashes for their URL routing (e.g. http://www.mysinglepageapplication.com/#welcomepage). Everything the hash changes, the hashchange event is raised.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function locationHashChanged() { | |
//if Google Analytics is available, then push the current location | |
if (_gaq !== undefined) { | |
_gaq.push(['_trackPageview', path]); | |
} | |
} | |
window.onhashchange = locationHashChanged; |