Skip to content

Instantly share code, notes, and snippets.

@daliborgogic
Last active July 1, 2019 09:51
Show Gist options
  • Save daliborgogic/91a01ff39ec2a30258b2a2fbe5555485 to your computer and use it in GitHub Desktop.
Save daliborgogic/91a01ff39ec2a30258b2a2fbe5555485 to your computer and use it in GitHub Desktop.
Vue.js SPA Google Analytics
// https://developers.google.com/analytics/devguides/collection/analyticsjs/single-page-applications
const isLocalhost = Boolean(
window.location.hostname === 'localhost' ||
// [::1] is the IPv6 localhost address.
window.location.hostname === '[::1]' ||
// 127.0.0.1/8 is considered localhost for IPv4.
window.location.hostname.match(/^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/)
)
// Option 1
router.onReady(() => {
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script',`https://www.google-analytics.com/analytics.js`,'ga')
ga('create', 'UA-XXXXXXXX-Y','auto')
// Prevent any hits from being sent to Google Analytics
if (isLocalhost) {
ga('set', 'sendHitTask', null)
}
router.afterEach((to, from) => {
ga('set', 'page', to.fullPath)
ga('send', 'pageview')
})
})
// Option 2
// While the JavaScript tracking snippet described above ensures the script will be loaded and executed
// asynchronously on all browsers, it has the disadvantage of not allowing modern browsers to preload the script.
router.onReady(() => {
window.ga=window.ga||function(){(ga.q=ga.q||[]).push(arguments)};ga.l=+new Date
// Trace debugging
// https://developers.google.com/analytics/devguides/collection/analyticsjs/debugging
// window.ga_debug = {trace: true}
ga('create', 'UA-XXXXXXXX-Y','auto')
if (isLocalhost) {
ga('set', 'sendHitTask', null)
}
router.afterEach((to, from) => {
ga('set', 'page', to.fullPath)
ga('send', 'pageview')
})
})
<!-- Option 2 -->
<script async src='https://www.google-analytics.com/analytics.js'></script>
<!-- Or with Trace debugging -->
<!-- <script async src='https://www.google-analytics.com/analytics_debug.js'></script> -->
</body>
</html>
@rognales
Copy link

is this compatible with history-mode?

@daliborgogic
Copy link
Author

daliborgogic commented Jun 24, 2019

@rognales Why do you think it's not compatible? You can use analitycs_debug.js in dev to test.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment