Skip to content

Instantly share code, notes, and snippets.

@jmileham
Created January 20, 2012 14:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jmileham/1647599 to your computer and use it in GitHub Desktop.
Save jmileham/1647599 to your computer and use it in GitHub Desktop.
Backbone + Google Analytics for hash urls
// Inspired by Kendall Buchanan, (https://github.com/kendagriff)
// Rewritten for hash URLs by John Mileham
// MIT licence
// Version 0.0.1
(function() {
var originalLoadUrl = Backbone.History.prototype.loadUrl;
// This cleans up fragment the same way that loadUrl does as of Backbone 0.5.3
Backbone.History.prototype.loadUrl = function(fragmentOverride) {
var fragment = this.fragment = this.getFragment(fragmentOverride);
if (window._gaq !== undefined) window._gaq.push(['_trackPageview', '/' + fragment]);
return originalLoadUrl.call(this, fragmentOverride);
};
var originalNavigate = Backbone.History.prototype.navigate;
// This doesn't clean up fragment before sending to GA, so there may be normalization issues
Backbone.History.prototype.navigate = function(fragment, triggerRoute) {
if (!triggerRoute && window._gaq !== undefined) window._gaq.push(['_trackPageview', '/' + fragment]);
return originalNavigate.call(this, fragment, triggerRoute);
};
}).call(this);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment