Last active
July 1, 2019 09:51
-
-
Save daliborgogic/91a01ff39ec2a30258b2a2fbe5555485 to your computer and use it in GitHub Desktop.
Vue.js SPA Google Analytics
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
// 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') | |
}) | |
}) |
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
<!-- 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> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
is this compatible with history-mode?