在没有Turbolink的Rails中添加Google Analytics [英] Adding google analytics in rails without turbolinks

查看:69
本文介绍了在没有Turbolink的Rails中添加Google Analytics的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于某些原因,我已从应用程序中删除了涡轮链接,现在当我尝试运行Google Analytics(分析)时,它不起作用.

I have removed turbolinks from my application for some reasons and now when I am trying to run google analytics, it is not working.

我使用了gem'google-analytics-rails'和此自定义解决方案.但是,它们都不起作用.知道如何在不使用Turbolinks的情况下如何在应用程序中添加google anayltics吗?

I used gem 'google-analytics-rails' and this customized solution. But none of them worked. Any idea how I can add google anayltics in my application without turbolinks?

推荐答案

我通常将其放置在ApplicationHelper中,就像这样

I typically just place this in the ApplicationHelper like so

module ApplicationHelper

  def ga_script
    tracking_id = ""
    if Rails.env.production?
      javascript_tag("(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', '#{tracking_id}', 'auto');")
    end
  end

  def ga_track
    javascript_tag("if(window.ga != undefined){ga('send', 'pageview');}")
  end

end

然后在布局文件中:

<head>
   <%= ga_script %>
</head>
<body>
...
   <%= ga_track %>
</body>

它很简单,可以使用/不使用Turbolinks.

Its simple and it works with/without Turbolinks.

或者,停止尝试使其复杂化,只需将GA脚本粘贴到布局的主体部分的底部即可.

Alternatively, stop trying to complicate it and simply paste the GA script at the bottom of the body section of your layout.

这篇关于在没有Turbolink的Rails中添加Google Analytics的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆