home
  • Blog
1.12
  • Getting Started
  • Concepts
  • The Object Model
  • Application
  • Templates
  • Routing
  • Components
  • Controllers
  • Models
  • Views
  • Enumerables
  • Testing
  • Configuring Ember.js
  • Ember Inspector
  • Cookbook
    • Introduction
    • Contributing
    • User Interface and Interaction
    • Event Handling & Data Binding
    • Helpers & Components
      • Introduction
      • Creating Reusable Social Share Buttons
      • A Spinning Button for Asynchronous Actions
      • Adding Google Analytics Tracking
    • Working with Objects
  • Understanding Ember.js
  • Contributing to Ember.js
Old Guides - You are viewing the guides for Ember v1.12.0.
Go to v5.0.0

Adding Google Analytics Tracking

Edit pencil

Problem

You want to add analytics to your Ember application.

Solution

Subscribe to the didTransition event inside your application router.

In the following examples we're using Google Analytics but it could be any other analytics product. Add Google analytic's base code to the html file that renders your ember app.

<html lang="en">
<head>
  <title>My Ember Site</title>
  <script type="text/javascript">

    var _gaq = _gaq || [];
    _gaq.push(['_setAccount', 'UA-XXXXX-Y']);

    (function() {
      var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
      ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
      var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
    })();

  </script>
</head>
<body>

</body>
</html>

Then reopen the application router and add this function. It will be called when didTransition is fired by the router.

app/router.js
var Router = Ember.Router.extend({
  // customization goes here
});

Router.reopen({
  notifyGoogleAnalytics: function() {
    return ga('send', 'pageview', {
        'page': this.get('url'),
        'title': this.get('url')
      });
  }.on('didTransition')
});

export default Router;

Discussion

The didTransition event is responsible for notifying listeners of any URL changes, in this example we are getting the path after the hash in the url so we can notify Google Analytics about moving between areas of the site.

left arrow
A Spinning Button for Asynchronous Actions
We've finished covering Helpers & Components. Next up: Working with Objects - Introduction
right arrow
On this page

  • Problem
  • Solution
  • Discussion
Team Sponsors Security Legal Branding Community Guidelines
Twitter GitHub Discord Mastodon

If you want help you can contact us by email, open an issue, or get realtime help by joining the Ember Discord.

© Copyright 2023 - Tilde Inc.
Ember.js is free, open source and always will be.


Ember is generously supported by
blue