Rails 5:如何让Google Analytics运行?

时间:2016-08-26 13:38:49

标签: heroku google-analytics ruby-on-rails-5 turbolinks railsapps

我尝试在 Rails 5 网站上安装Google Analytics,添加由Jonathon Wolfe创建并在Nick Reed的 Turbolinks兼容性网站上提供的Google Analytics跟踪脚本。

Google Analytics仍然无法从我的网站获取跟踪数据。我错过了什么?

2 个答案:

答案 0 :(得分:2)

I use slim templating, so make changes according to your templating engine. In application.html.slim in head initialize ga

javascript:
  (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-XXXXXXX-XX', 'auto');
  ga('send', 'pageview');

in ga.js.coffee

document.addEventListener 'turbolinks:load', (event) ->
  if typeof ga is 'function'
    ga('set', 'location', event.data.url)
    ga('send', 'pageview')

Bonus. I also use infinite scroll, so when I load data in index.js.erb I use this to send another page view to ga

ga('send', 'pageview');
... rest of the code

答案 1 :(得分:0)

如果您将此页http://reed.github.io/turbolinks-compatibility/google_analytics.html与上面发布的设置一起使用,则需要将application.js更改为application.js.coffee。所有代码都是用coffeescript编写的。