Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
How I add GA to my Ember apps.
# app/instance-initializers/google-analytics.js
import ENV from "./config/environment";
export function initialize(application) {
let fastboot = application.lookup('service:fastboot');
window.dataLayer = window.dataLayer || [];
if (!fastboot.get('isFastBoot')) {
let body = document.getElementsByTagName('body').item(0);
let analyticsScript = document.createElement('script');
analyticsScript.setAttribute('type', 'text/javascript');
analyticsScript.setAttribute('async', '');
analyticsScript.setAttribute('src', `https://www.googletagmanager.com/gtag/js?id=${ENV.googleAnalyticsTrackingId}`);
body.appendChild(analyticsScript);
window.dataLayer.push(['js', new Date()]);
window.dataLayer.push(['config', ENV.googleAnalyticsTrackingId]);
}
}
export default {
name: 'google-analytics',
initialize
};
# app/router.js
import EmberRouter from '@ember/routing/router';
import config from './config/environment';
import { on } from '@ember/object/evented';
import { inject as service } from "@ember/service";
const Router = EmberRouter.extend({
googleAnalytics: service('google-analytics'),
location: config.locationType,
rootURL: config.rootURL,
sendAnalytics: on('didTransition', function() {
this.googleAnalytics.gtag('config', config.googleAnalyticsTrackingId, { page_path: this.url });
})
});
Router.map(function() {});
export default Router;
# app/services/google-analytics.js
import Service from '@ember/service';
export default Service.extend({
gtag() {
window.dataLayer.push(arguments);
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.