Created
January 14, 2019 01:59
-
-
Save jimsynz/15dda275bf7171be0becf2d807d2daf9 to your computer and use it in GitHub Desktop.
How I add GA to my Ember apps.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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 | |
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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