Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ember CLI and Google Analytics

Tags:

ember.js

According to the docs, you just need to embed the analytics code and reopen the Router. The latter seems unclear to me.

I've placed the embedded code on index.html, then created the following

app/reopens/router.js

import Router from '../router';

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

app/app.js: Added the import...

import './reopens/router';

This results in a fatal error when viewing the site: Uncaught ReferenceError: ga is not defined

How do you make the ga function visible to this observer?

like image 926
bitsoflogic Avatar asked Mar 23 '26 18:03

bitsoflogic


1 Answers

The problem is that on the first run through of the didTransition, the method is missing as that part of the script has not been executed.

Is this a problem? Actually no. The purpose of didTransition in this instance is to capture when a transition occurs as the supplied javascript from Google with capture to initial local of the page. All is needed is a check to see if 'ga' exists.

  1. Add the recommended javascript to the index.html of your ember app from Google (https://developers.google.com/analytics/devguides/collection/analyticsjs/).

  2. Modify your code to include a check to see if ga is undefined:

    import Router from '../router';
    
    Router.reopen({
        notifyGoogleAnalytics: function() {
            if (typeof ga != 'function') { return; }
            return ga('send', 'pageview', {
              'page': this.get('url'),
              'title': this.get('url')
            });
        }.on('didTransition')
    });
    

This is variation of what I have for an ember-cli based app. Let me know if it works.

like image 98
Andrew Baker Avatar answered Mar 25 '26 19:03

Andrew Baker