js999
js999

Reputation: 2083

Tracking Site Activity (Google Analytics) using Backbone

I am looking the best way to track the Site Activity in Google Analytics for a web app made with Backbone and Requires.

Looking At Google's Page, I found this drop-in plugin - Backbone.Analytics.

My questions are:
1) using Backbone.Analytics, should I change backbone.analytics.js in order to add _gaq.push(['_setAccount', 'UA-XXXXX-X']);?
2) Are there other possible solutions/plugins?

Upvotes: 9

Views: 5067

Answers (8)

v9Damon
v9Damon

Reputation: 1

Just posting an update to this question as it seems to be one I get a lot from backbone.js developers I know or work with who seem to fall at the last hurdle.

The Javascript:

App.trackPage = function() {
 var url;
 if (typeof ga !== "undefined" && ga !== null) {
  url = Backbone.history.getFragment();
  return ga('send', 'pageview', '/' + url);
 }
};

Backbone.history.on("route", function() {
 return App.trackPage();
});

The Tracking Snippet:

<head>
 <script>
  (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||
  function(){(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();
  a=s.createElement(o),m=s.getElementsByTagName(o)[0];a.async=1;
  a.src=g;m.parentNode.insertBefore(a,m)})(window,document,'script',
  '//www.google-analytics.com/analytics.js','ga');

  ga('create', 'UA-XXXXXXXX-X', 'auto');
 </script>
</head>

The Tracking Snippet should be available on any page you wish to track activity. This could be your index.html where all your content is injected, but some sites may have multiple static pages or a mix. You can include the ga('send') function if you wish, but it will only fire on a page load.

I wrote a blog post that goes in to more detail, explaining rather than showing, the full process which you can find here: http://v9solutions.co.uk/tech/2016/02/15/how-to-add-google-analytics-to-backbone.js.html

Upvotes: 0

Akhorus
Akhorus

Reputation: 2273

All answers seem to be almost good, but out-of-date (Sept. 2015). Following this Google devs guide: https://developers.google.com/analytics/devguides/collection/analyticsjs/single-page-applications Here's my version of the solution (I've added the suggested call to ga('set'...) ):

MyRouter = Backbone.Router.extend
    ...
    initialize: () ->
        # Track every route and call trackPage
        @bind 'route', @trackPage

    trackPage: () ->
        url = Backbone.history.getFragment()
        # Add a slash if neccesary
        if not /^\//.test(url) then url = '/' + url
        # Analytics.js code to track pageview
        global.ga('set', {page: url})
        global.ga('send', 'pageview')
    ...

Upvotes: 0

Allan Veloso
Allan Veloso

Reputation: 6389

If you use the new universal analytics.js, you can do that like this:

var Router = Backbone.Router.extend({
    routes: {
        "*path":                        "page",
    },

    initialize: function(){
        // Track every route and call trackPage
        this.bind('route', this.trackPage);
    },

    trackPage: function(){
        var url = Backbone.history.getFragment();
        // Add a slash if neccesary
        if (!/^\//.test(url)) url = '/' + url;
        // Analytics.js code to track pageview
        ga('send', {
            'hitType': 'pageview',
            'page': url
        });
    },

    // If you have a method that render pages in your application and
    // call navigate to change the url, you can call trackPage after
    // this.navigate()
    pageview: function(path){
        this.navigate(path);
        pageView = new PageView;
        pageView.render();
        // It's better call trackPage after render because by default
        // analytics.js passes the meta tag title to Google Analytics
        this.trackPage();
    }
}

Upvotes: 0

Jose Browne
Jose Browne

Reputation: 4622

Just figured i'd share how i'm doing it. This might not work for larger apps but I like manually telling GA when to track page views or other events. I tried binding to "all" or "route" but couldn't quite get it to record all the actions that I need automajically.

App.Router = BB.Router.extend({
    //...
    track: function(){
        var url = Backbone.history.getFragment();

        // Add a slash if neccesary
        if (!/^\//.test(url)) url = '/' + url;

        // Record page view
        ga('send', {
            'hitType': 'pageview',
            'page': url
        });
    }
});

So i just call App.Router.Main.track(); after I navigate or do anything i want to track.

Do note that I use the new Analytics.js tracking snippet which is currently in public beta but has an API so intuitive that it eliminates the need for a plugin to abstract any complexity what so ever. For example: I keep track of how many people scroll to end of an infinite scroll view like this:

onEnd: function(){
    ga('send', 'event', 'scrollEvents', 'Scrolled to end');
}

enter image description here Good luck.

Upvotes: 3

Dan
Dan

Reputation: 2769

I wrote a small post on this, hope it helps someone:

http://sizeableidea.com/adding-google-analytics-to-your-backbone-js-app/

var appRouter = Backbone.Router.extend({
     initialize: function() {
        this.bind('route', this.pageView);  
    },  
    routes: {
        'dashboard': 'dashboardPageHandler'
    },
    dashboardPageHandler: function() {
      // add your page-level logic here...    
    },
    pageView : function(){  
     var url = Backbone.history.getFragment();

     if (!/^\//.test(url) && url != ""){
          url = "/" + url;
      }

      if(! _.isUndefined(_gaq)){
         _gaq.push(['_trackPageview', url]);
      }  
   }   
});

var router = new appRouter();

Backbone.history.start();

Upvotes: 1

Arnaud Valle
Arnaud Valle

Reputation: 1861

Regarding other possible solutions/plugins, I've used https://github.com/aterris/backbone.analytics in a few projects and it works quite well as well. It also has options for a few more things like event tracking which can be handy at some point in your analytics integration.

Upvotes: 0

algiecas
algiecas

Reputation: 2128

I prefer "do it yourself" style :) It's really simple:

var Router = Backbone.Router.extend({

    initialize: function()
    {
        //track every route change as a page view in google analytics
        this.bind('route', this.trackPageview);
    },

    trackPageview: function ()
    {
        var url = Backbone.history.getFragment();

        //prepend slash
        if (!/^\//.test(url) && url != "")
        {
            url = "/" + url;
        }

        _gaq.push(['_trackPageview', url]);
    }
}

And you add google analytics script to your page as usual.

Upvotes: 17

KendallB
KendallB

Reputation: 4807

You shouldn't have to change anything. Just add your Google Analytics code snippet, like normal, and include Backbone.Analytics as you would any other Javascript library.

Upvotes: 3

Related Questions