bgarret / google-analytics-rails

Rails 3 helpers to manage google analytics tracking. Mostly intended for small to medium websites.
323 stars 44 forks source link

Support Turbolinks #29

Open mebibou opened 9 years ago

mebibou commented 9 years ago

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

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

spodlecki commented 8 years ago

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

asecondwill commented 7 years ago

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

spodlecki commented 7 years ago

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

SimonVillage commented 7 years ago

We had to change the javascript part:

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

Updated above snippet to use the pathname in the pageview event