Rails 4 turbolinks with Google Analytics

前端 未结 8 840
陌清茗
陌清茗 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:43

    A quick glance into the source shows, that the only thing this gem does is to add some javascript to the asset-pipeline

    # google-analytics-turbolinks/lib/assets/javascripts/google-analytics-turbolinks.js.coffee
    if window.history?.pushState and window.history.replaceState
      document.addEventListener 'page:change', (event) =>
    
        # Google Analytics
        if window.ga != undefined
          ga('set', 'location', location.href.split('#')[0])
          ga('send', 'pageview')
        else if window._gaq != undefined
          _gaq.push(['_trackPageview'])
        else if window.pageTracker != undefined
          pageTracker._trackPageview();
    

    That's all there is to it. You can either use the gem or add something like this code-snippet manually to your javascript-assets.

提交回复
热议问题