Rails 4 turbolinks with Google Analytics Rails 4 turbolinks with Google Analytics ruby-on-rails ruby-on-rails

Rails 4 turbolinks with Google Analytics


I like vladCovaliov's solution because it seems most new accounts use Universal Analytics by default (which is also better featured in my opinion). However, I think this answer needs to be combined with the other suggestions that comment out the initial pageview, use the page:change event, and track pageviews, not events.

For example, in your <head>:

<% if Rails.env.production? %>  <script>    (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','//www.google-analytics.com/analytics.js','ga');    ga('create', 'UA-XXXXXXXX-X', 'auto');    //ga('send', 'pageview');  </script><% else %>  <script>    function ga () {      var params = Array.prototype.slice.call(arguments, ga.length);      console.log("GoogleAnalytics: " + params);    };  </script><% end %>

And then in a js file you have loaded through the asset pipeline:

$(document).on('page:change', function() {  ga('send', 'pageview', window.location.pathname);});

This will record a pageview for each page you load with or without Turbolinks. Note that the window.location.pathname is required, otherwise you can get the URL of the first page loaded for all the subsequent page loads. (This also gives you a nice place to edit the URL reported if you wanted to, say, strip out :id path segments from RESTful URLs.)

You can also then easily call:

ga('send', "event", category, action, label, count);

To report Events for other interesting javascript events in your site.


I've went with a different approach that I saw on some web site but it seems reasonable.

Add GA to your header like usual but with a small modification of commenting out the trackPageview event from happening automatically.

<script type="text/javascript">  var _gaq = _gaq || [];  _gaq.push(['_setAccount', 'UA-FOOBAR']);  //_gaq.push(['_trackPageview']);  (function() {    var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;    ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);  })();</script>

Then add this somewhere in your body because the body gets reloaded for turbolinks.

<% if Rails.env.production? %>  <script>_gaq.push(['_trackPageview']);</script><% end %>

The production check is optional but this is a nice way to not have GA track localhost hits if you're actively developing. The other perk is you don't have to worry about messing with page:change or page:load bindings and that you can be confident that it'll work on any browser that's trackable by GA without having to worry about double hits or anything weird.


I think a better idea is to use the new Universal Analytics (from analytics.js file).

Universal Analytics Solution

  (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','//www.google-analytics.com/analytics.js','ga');  ga('create', "#{GA_UA}", "#{GA_URL}");  ga('send', 'pageview');

And then when you wanna send an event for example, you can use

<script> ga('send', "event", "#{category}", "#{action}", "#{label}", "#{count}"); </script>

Be careful to render this code in the body, and not in the head. Turbo-links only replaces the body.

And also be careful:

1) The GA_URL needs to match your pages's url

2) The Events show up in real time, but in the events tab, they only appear after 24h +

3) Your account's property need to be 'Universal' for this solution to work

Universal Analytics docs:

https://support.google.com/analytics/answer/2790010?hl=en&ref_topic=2790009