Rails 4 turbolinks with Google Analytics

前端 未结 8 792
陌清茗
陌清茗 2020-12-07 19:14

I\'m wondering what is the best way to implement Google Analytics tracking code along with the turbo linking in Rails 4. Will the normal snippet work? I\'ve also seen a gems

8条回答
  •  既然无缘
    2020-12-07 19:44

    I appreciate scottwb's answer, but unfortunately it does not work with Rails 5. In Rails 5 Turbolinks events were renamed. The 'page:change' event was renamed to 'turbolinks:load'. This is why his example does not work anymore.

    You can find an overview of how they were renamed here: https://github.com/turbolinks/turbolinks/blob/master/src/turbolinks/compatibility.coffee

    Since this took me some time to figure out, I am posting the proper Rails 5 implementation for everybody coming after me.

    Put the following code in your

      
    

    And then in a js file (eg. application.js) in you asset pipeline:

    $(document).on('turbolinks:load', function() {
       ga('send', 'pageview', window.location.pathname + window.location.search);
    });
    

    Remember to replace "UA-XXXXXXXX-X" with your Google Analytics ID.

提交回复
热议问题