使用 Rails 4 进行 Google 分析 [英] Google analytics with rails 4
问题描述
在我的 rails 4 项目中实施谷歌分析时遇到了一些困难.我将跟踪代码包含在布局文件的底部,甚至尝试按照建议删除 turbolinks 在这里 但是我谷歌仍然无法检测到这个跟踪cookie.有什么想法吗?
I am having a bit of difficulty implementing google analytics to my rails 4 project. I included the tracking code to the bottom of my layouts file and have even tried to remove turbolinks as suggested here however i google is still unable to detect this tracking cookie. Any ideas ?
推荐答案
我几天前设置了 Google Analytics..
I set up Google Analytics a few days before..
1.) Turbolink 解决方法
使用 Turbolinks,Google Analytics JavaScript 库不足以记录每次页面更新的页面访问.
With Turbolinks, the Google Analytics JavaScript library is not sufficient to record a page visit for every page update.
应对方法应在每个页面上加载,并且可以作为应用程序范围的资产包含(它将在 Turbolinks 之前加载).
The workaround should be loaded on every page and it can be included as an application-wide asset (it will load before Turbolinks).
添加文件 app/assets/javascripts/analytics.js.coffee
以包含 Turbolinks 解决方法:
Add the file app/assets/javascripts/analytics.js.coffee
to include the Turbolinks workaround:
app/assets/javascripts/analytics.js
// Coffee
$(document).on 'page:change', ->
if window._gaq?
_gaq.push ['_trackPageview']
else if window.pageTracker?
pageTracker._trackPageview()
// Javascript
$(document).on('page:change', function() {
if (window._gaq != null) {
return _gaq.push(['_trackPageview']);
} else if (window.pageTracker != null) {
return pageTracker._trackPageview();
}
});
2.) 创建页脚部分
只需在 app/views/layouts
中创建一个 Partial -> _footer.html.erb
Just create a a Partial into app/views/layouts
-> _footer.html.erb
然后在 application.html.erb 上调用 Partial -> <%= render 'layouts/footer' %>
Then Call your Partial on your application.html.erb -> <%= render 'layouts/footer' %>
在页脚中插入 Analytics 跟踪代码:
Insert into your Footer the Analytics Track Code:
<script>
(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', 'herokuapp.com');
ga('send', 'pageview');
</script>
您必须将 UA-XXXXXXX-XX 替换为您的跟踪 ID,并将 herokuapp.com 替换为您的域(如果有).
You must replace UA-XXXXXXX-XX with your tracking ID, and herokuapp.com with your Domain if you have any.
这篇关于使用 Rails 4 进行 Google 分析的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!