google-analytics-rails icon indicating copy to clipboard operation
google-analytics-rails copied to clipboard

Support Turbolinks

Open mebibou opened this issue 9 years ago • 5 comments

Do you have any plans to support Turbolinks? like described here:

http://reed.github.io/turbolinks-compatibility/google_analytics.html

mebibou avatar Nov 09 '15 06:11 mebibou

I feel like that is something that's better left to the app's specific requirements. What you could do, is still use the init tag, but pass skip_pageview: true as an option.

Then using the coffeescript in your ticket, you can run the ga commands.

Would just need to make sure that turbolinks doesn't reload the GA scripts, which I believe you can do by placing the init tag in the head

spodlecki avatar Jan 12 '16 16:01 spodlecki

Think it needs to work with Turbo Links as that's standard for rails.

asecondwill avatar Jan 05 '17 15:01 asecondwill

To accomplish what you're looking for, here is a snippet of code that'll get you started. I welcome any PR that would like to include a JavaScript class for this style, but I still feel its best left to the application.

application.html.erb

<html>
  <head>
  <%= analytics_init(skip_pageview: true) %>
  </head>
  ....
</html>

Javascript in app

(function() {
  document.addEventListener("turbolinks:load", function() {
    ga('send', 'pageview', window.location.pathname);
  });
})();

Turbo Links will execute any javascripts you place in the body as the different pages load too, so there is always that option as well.

<body>
  <div>Hello world</div>
  <%= GA::Events::TrackPageview.new %>
</body>

*all untested

spodlecki avatar Jan 05 '17 16:01 spodlecki

We had to change the javascript part:

(function() {
  document.addEventListener("turbolinks:load", function() {
    ga('send', 'pageview', window.location.pathname);
  });
})();

SimonVillage avatar Jul 31 '17 09:07 SimonVillage

Updated above snippet to use the pathname in the pageview event

spodlecki avatar Aug 16 '17 11:08 spodlecki