将Google Analytics添加到Rails 4.2应用程序 [英] Adding Google Analytics to Rails 4.2 app

查看:113
本文介绍了将Google Analytics添加到Rails 4.2应用程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经使用Heroku部署了一个Rails 4.2应用程序,并且试图将Google Analytics添加到它。但是,Google Analytics并未收集任何会话。



有什么建议为什么以及如何解决这个问题?

CODE



/app/layouts/_footer.html.erb:

 <%if Rails.env.production? %GT; 
< 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-XXXXXXXX-X','herokuapp.com');
ga('send','pageview');

< / script>
<%end%>

/app/layouts/application.html.erb:

 <!DOCTYPE html> 
< html>
< head>
< title>标题< / title>
<%= Gon :: Base.render_data({})%>
<%= stylesheet_link_tag'application',media:'all','data-turbolinks-track'=> true%>
<%= javascript_include_tag'application','data-turbolinks-track'=> true%>
<%= csrf_meta_tags%>
< meta name =viewportcontent =width = device-width,initial-scale = 1.0>
< / head>
< body>

< div class =container>
<%= yield%>
< / div>

<%=渲染'布局/页脚'%>

< / body>
< / html>



/app/assets/javascripts/analytics.js.coffee:

  $(document).on'page:change', - > 
如果window._gaq?
_gaq.push ['_trackPageview']
else if window.pageTracker?
pageTracker._trackPageview()

/app/assets/javascripts/application.js:

  // =需要jquery 
// =需要分析
// =需要引导
// =要求jquery_ujs
// =要求jquery.ui.all
// =要求Chart
// =要求jquery.turbolinks
// =要求lodash
// = require_tree。

Gemfile:

  source'https://rubygems.org'

gem'rails','4.2.2'
gem'bootstrap-sass','3.2.0.0'
gem'sass-rails','5.0.2'
gem'uglifier','2.5.3'
gem'coffee-rails','4.1.0'
gem 'jquery-rails','4.0.3'
gem'jquery-ui-rails','〜> 4.2.1'
gem'turbolinks','2.3.0'
gem'jquery-turbolinks'
gem'jbuilder','2.2.3'
gem'sdoc' ,'0.4.0',group::doc
gem'chart-js-rails'
gem'gon'
gem'lodash-rails'

group :development,:test do
gem'sqlite3','1.3.9'
gem'byebug','3.4.0'
gem'web-console','2.0.0。 beta3'
gem'spring','1.1.3'
end

group:production do
gem'pg','0.17.1'
gem'rails_12factor','0.0.2'
end


解决方案 div>

你添加脚本的方式是错误的,因为Turbolinks不会工作,你知道_footer中的代码不会按预期运行,因为这段代码不会按预期运行因为Turbolinks重新加载。



我会给你我的自定义执行所有我的Rails应用程序的ogle分析。



在app / assets / javascripts中创建一个名为google_analytics.js.coffee的新文件并添加以下脚本:

  class @GoogleAnalytics 

@load: - >
#Google Analytics取决于全局_gaq数组。窗口是全球范围。
window._gaq = []
window._gaq.push [_setAccount,GoogleAnalytics.analyticsId()]

#创建一个脚本元素并将其插入到DOM
ga = document.createElement(script)
ga.type =text / javascript
ga.async = true
ga.src =((如果https:是document.location.protocol然后是https:// sslelsehttp:// www))+.google-analytics.com / ga.js
firstScript = document.getElementsByTagName(script )[0]
firstScript.parentNode.insertBefore ga,firstScript

#如果支持Turbolinks,请在page:change上设置一个回调以跟踪浏览量。
#如果不支持,只需立即跟踪网页浏览。
如果typeof Turbolinks is not'undefined'和Turbolinks.supported
document.addEventListenerpage:change,( - >
GoogleAnalytics.trackPageview()
),true
else
GoogleAnalytics.trackPageview()

@trackPageview:(url) - >
除非GoogleAnalytics.isLocalRequest()
如果url
window._gaq.push [_trackPageview,url]
else
window._gaq.push [_trackPageview ]
window._gaq.push [_trackPageLoadTime]

@isLocalRequest: - >
GoogleAnalytics.documentDomainIncludeslocal

@documentDomainIncludes:(str) - >
document.domain.indexOf(str)isnt -1

@analyticsId: - >
#您的Google Analytics(分析)ID在这里...
'UA-xxxxxxxx-x'

GoogleAnalytics.load()

正如您所看到的,它增加了对Turbolinks的支持,这是将Google分析添加到您的应用的一种干净且更好的方式。希望它适合你。


I've got a Rails 4.2 app that I've deployed with Heroku and I've tried to add Google Analytics to it. However, Google Analytics isn't picking up any sessions.

Any suggestions why and how to resolve this?

CODE

/app/layouts/_footer.html.erb:

<% if Rails.env.production? %>
  <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-XXXXXXXX-X', 'herokuapp.com');
    ga('send', 'pageview');

  </script>
<% end %>

/app/layouts/application.html.erb:

<!DOCTYPE html>
<html>
<head>
  <title>Title</title>
<%= Gon::Base.render_data({}) %>
  <%= stylesheet_link_tag    'application', media: 'all', 'data-turbolinks-track' => true %>
  <%= javascript_include_tag 'application', 'data-turbolinks-track' => true %>
  <%= csrf_meta_tags %>
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>

<div class="container">
    <%= yield %>
</div>

<%= render 'layouts/footer' %>

</body>
</html>

/app/assets/javascripts/analytics.js.coffee:

$(document).on 'page:change', ->
 if window._gaq?
  _gaq.push ['_trackPageview']
 else if window.pageTracker?
  pageTracker._trackPageview()

/app/assets/javascripts/application.js:

//= require jquery
//= require analytics
//= require bootstrap
//= require jquery_ujs
//= require jquery.ui.all
//= require Chart
//= require jquery.turbolinks
//= require lodash
//= require_tree .

Gemfile:

source 'https://rubygems.org'

gem 'rails',                '4.2.2'
gem 'bootstrap-sass',       '3.2.0.0'
gem 'sass-rails',           '5.0.2'
gem 'uglifier',             '2.5.3'
gem 'coffee-rails',         '4.1.0'
gem 'jquery-rails',         '4.0.3'
gem 'jquery-ui-rails', '~> 4.2.1'
gem 'turbolinks',           '2.3.0'
gem 'jquery-turbolinks'
gem 'jbuilder',             '2.2.3'
gem 'sdoc',                 '0.4.0', group: :doc
gem 'chart-js-rails'
gem 'gon'
gem 'lodash-rails'

group :development, :test do
  gem 'sqlite3',     '1.3.9'
  gem 'byebug',      '3.4.0'
  gem 'web-console', '2.0.0.beta3'
  gem 'spring',      '1.1.3'
end

group :production do
  gem 'pg',             '0.17.1'
  gem 'rails_12factor', '0.0.2'
end

解决方案

The way you are adding your script is the wrong way, since it will not work due to Turbolinks, you know the code you have in your _footer won't be running as expected since that piece of markup won't reload because of Turbolinks.

I will give you my custom implementation of google analytics for all my rails apps.

In your app/assets/javascripts create a new file called google_analytics.js.coffee and add the following script:

class @GoogleAnalytics

  @load: ->
    # Google Analytics depends on a global _gaq array. window is the global scope.
    window._gaq = []
    window._gaq.push ["_setAccount", GoogleAnalytics.analyticsId()]

    # Create a script element and insert it in the DOM
    ga = document.createElement("script")
    ga.type = "text/javascript"
    ga.async = true
    ga.src = ((if "https:" is document.location.protocol then "https://ssl" else "http://www")) + ".google-analytics.com/ga.js"
    firstScript = document.getElementsByTagName("script")[0]
    firstScript.parentNode.insertBefore ga, firstScript

    # If Turbolinks is supported, set up a callback to track pageviews on page:change.
    # If it isn't supported, just track the pageview now.
    if typeof Turbolinks isnt 'undefined' and Turbolinks.supported
      document.addEventListener "page:change", (->
        GoogleAnalytics.trackPageview()
      ), true
    else
      GoogleAnalytics.trackPageview()

  @trackPageview: (url) ->
    unless GoogleAnalytics.isLocalRequest()
      if url
        window._gaq.push ["_trackPageview", url]
      else
        window._gaq.push ["_trackPageview"]
      window._gaq.push ["_trackPageLoadTime"]

  @isLocalRequest: ->
    GoogleAnalytics.documentDomainIncludes "local"

  @documentDomainIncludes: (str) ->
    document.domain.indexOf(str) isnt -1

  @analyticsId: ->
    # your google analytics ID(s) here...
    'UA-xxxxxxxx-x'

GoogleAnalytics.load()

As you can see it adds support for Turbolinks, this is a clean and better way to add Google analytics to your app. Hope it works for you.

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

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