Google Analytics with Rails 5 and Turbolinks

0

Go to Admin > Property > Tracking Info > Tracking Code to get your 'UA-xxxxxxx-x'

apps/views/application/_analytics.html.erb
<% if Rails.env.production? %>
<script async src="https://www.googletagmanager.com/gtag/js?id=UA-xxxxxxx-x"></script>
<script>
  window.dataLayer = window.dataLayer || [];
  function gtag(){dataLayer.push(arguments);}
  gtag('js', new Date());
  gtag('config', 'UA-xxxxxxx-x');

    document.addEventListener('turbolinks:load', event => {
        if (typeof gtag === 'function') {
            gtag('config', 'UA-xxxxxxx-x', {
                'page_location': event.data.url
            });
        }
    });
</script>
<% end %>
application.html.erb
<head>
    <%= csrf_meta_tags %>
    <%= csp_meta_tag %>
    <%= stylesheet_link_tag    'application', media: 'all', 'data-turbolinks-track': 'reload' %>
    <%= render "analytics" %>
    <%= javascript_include_tag 'application', 'data-turbolinks-track': 'reload' %>
</head>

  • 0 posts
  • 0 subtopics
  • 10 months ago by vince