Google Analytics for Single-Page Web Apps with Ember

Single-page web apps are awesome — they have so much flexibility and power. Unfortunately, when users browse a single-page web app, Google Analytics doesn’t work as intended when changing “pages”. Under the hood of these engines lies DOM manipulation to change what is displayed on screen, but Google Analytics watches for page changes. Fortunately, Ember makes it easy to hook into the “page changes” to allow for tracking.

The implementation is fairly simple — you need an initializer and the standard Google Analytics tracking snippet. As normal, follow the instructions to place the analytics code into your index.html. If you are serving up you app through Rails or another engine that builds your pages, place the code in the page that loads your Ember files. The code should look similar to this:

  (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
  ga('create', 'UA-XXXXXXX-X', 'example.com');
  ga('send', 'pageview');

Once you have that in place, you can place this code into your initializers:

Ember.GoogleAnalyticsTrackingMixin = Ember.Mixin.create
  pageHasGa: ->
    window.ga and typeof window.ga is "function"
  trackPageView: (page) ->
    if @pageHasGa()
      unless page
        loc = window.location
        page = (if loc.hash then loc.hash.substring(1) else loc.pathname + loc.search)
      ga "send", "pageview", page
  trackEvent: (category, action) ->
    ga "send", "event", category, action  if @pageHasGa()
  name: "googleAnalytics"
  initialize: (container, application) ->
    router = container.lookup("router:main")
    router.on "didTransition", ->
      @trackPageView @get("url")
Ember.Router.reopen Ember.GoogleAnalyticsTrackingMixin

The initializer will run and inject a tracking object into the Ember router. When the Ember router changes views, much like a page change, it will then check if the window.ga object is available (the Google Analytics code we placed earlier) and fire off a page change message. With the available Google Analytics API, you can now track events and other things throughout your Ember app by using the window.ga object.