-
-
Save the-bass/545653241530f8f2c2e16371bec56f20 to your computer and use it in GitHub Desktop.
<%# Put this code snippet between the <head></head>-tags in your application layout and %> | |
<%# replace 'UA-XXXXXXXX-X' with your own unique Google Analytics Tracking ID %> | |
<%# ... %> | |
<head> | |
<%# ... %> | |
<% if Rails.env.production? %> | |
<script type="text/javascript"> | |
(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-X', 'auto'); | |
</script> | |
<% end %> | |
</head> | |
<%# ... %> |
# Put this file into your assets/javascripts/ folder and assure | |
# it gets loaded by checking or editing your assets/javascripts/application.js | |
# file as appropriate | |
document.addEventListener 'turbolinks:load', (event) -> | |
if typeof ga is 'function' | |
ga('set', 'location', event.data.url) | |
ga('send', 'pageview') |
Thank you!
Thank you
Great! Thanks.
In case this is helpful for someone... I had some trouble making it work because of my google analytics code (had to create a different one) - but this code definitely works.
Exactly what I was looking for, thank you !
Or if you're using the new gtag manager:
$(document).on('turbolinks:load', function () {
gtag('config', 'UA-XXXXXXXX-X', {'page_path': window.location.pathname});
});
Per their instructions here:
https://developers.google.com/analytics/devguides/collection/gtagjs/single-page-applications
under Tracking virtual pageviews
Thanks @seebq. Newest site I was working on required the new gtag version and I couldn't figure out what method to call. Your solution worked.
This is what I use with the gtag manager, using slim and CoffeeScript:
application.html.slim
- if Rails.env.production?
= javascript_include_tag 'https://www.googletagmanager.com/gtag/js?id=UA-XXXX-X'
javascript:
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
google_analytics.js.coffee
$(document).on 'turbolinks:load', ->
if typeof gtag is 'function'
gtag('config', UA-XXXX-X', {'page_path': window.location.pathname})
@zedtux