使用谷歌分析的Rails 4 turbolinks

时间:2021-10-19 15:16:34

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 for this but I'm not sure what it does.

我想知道实现谷歌分析跟踪代码以及Rails 4中的涡轮链接的最佳方式是什么。正常的代码片段可以工作吗?我也见过一些宝石,但我不确定它是做什么的。

8 个解决方案

#1


13  

I think a better idea is to use the new Universal Analytics (from analytics.js file).

我认为更好的办法是使用新的通用分析(来自分析)。js文件)。

Universal Analytics Solution

通用的分析解决方案

  (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', "#{GA_UA}", "#{GA_URL}");
  ga('send', 'pageview');

And then when you wanna send an event for example, you can use

然后当你想发送一个事件的时候,你可以使用。

<script> ga('send', "event", "#{category}", "#{action}", "#{label}", "#{count}"); </script>

Be careful to render this code in the body, and not in the head. Turbo-links only replaces the body.

要小心在主体中而不是头部中呈现此代码。涡轮连杆只能代替车身。

And also be careful:

也要小心:

1) The GA_URL needs to match your pages's url

1) GA_URL需要匹配页面的url

2) The Events show up in real time, but in the events tab, they only appear after 24h +

2)事件实时显示,但在Events选项卡中,它们仅在24小时以上显示

3) Your account's property need to be 'Universal' for this solution to work

3)您的帐户的属性必须是“通用的”,才能使这个解决方案发挥作用

Universal Analytics docs:

通用分析文档:

https://support.google.com/analytics/answer/2790010?hl=en&ref_topic=2790009

https://support.google.com/analytics/answer/2790010?hl=en&ref_topic=2790009

#2


28  

I like vladCovaliov's solution because it seems most new accounts use Universal Analytics by default (which is also better featured in my opinion). However, I think this answer needs to be combined with the other suggestions that comment out the initial pageview, use the page:change event, and track pageviews, not events.

我喜欢vladCovaliov的解决方案,因为大多数新帐户默认使用通用分析(这在我看来也更有特色)。但是,我认为这个答案需要与其他建议结合起来,这些建议注释掉最初的pageview,使用page:change event,并跟踪pageviews,而不是events。

For example, in your <head>:

例如,在你的:

<% 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', 'auto');
    //ga('send', 'pageview');
  </script>
<% else %>
  <script>
    function ga () {
      var params = Array.prototype.slice.call(arguments, ga.length);
      console.log("GoogleAnalytics: " + params);
    };
  </script>
<% end %>

And then in a js file you have loaded through the asset pipeline:

然后在一个js文件中,通过资产管道加载:

$(document).on('page:change', function() {
  ga('send', 'pageview', window.location.pathname);
});

This will record a pageview for each page you load with or without Turbolinks. Note that the window.location.pathname is required, otherwise you can get the URL of the first page loaded for all the subsequent page loads. (This also gives you a nice place to edit the URL reported if you wanted to, say, strip out :id path segments from RESTful URLs.)

这将为您加载的每个页面或没有Turbolinks的页面记录一个页面视图。注意,window.location。路径名是必需的,否则您可以获得为所有后续页面加载而加载的第一个页面的URL。(这也为您提供了一个编辑报告的URL的好地方,例如,如果您想从RESTful URL中删除:id路径段。)

You can also then easily call:

你也可以很容易地打电话:

ga('send', "event", category, action, label, count);

To report Events for other interesting javascript events in your site.

为站点中其他有趣的javascript事件报告事件。

#3


14  

I've went with a different approach that I saw on some web site but it seems reasonable.

我采用了一种不同的方法,我在一些网站上看到过,但似乎是合理的。

Add GA to your header like usual but with a small modification of commenting out the trackPageview event from happening automatically.

像往常一样将GA添加到你的标题中,但是对trackPageview事件的注释做一个小修改。

<script type="text/javascript">
  var _gaq = _gaq || [];
  _gaq.push(['_setAccount', 'UA-FOOBAR']);
  //_gaq.push(['_trackPageview']);

  (function() {
    var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
    ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
  })();
</script>

Then add this somewhere in your body because the body gets reloaded for turbolinks.

然后把它添加到你身体的某个地方,因为你的身体会被重新装上松脂。

<% if Rails.env.production? %>
  <script>_gaq.push(['_trackPageview']);</script>
<% end %>

The production check is optional but this is a nice way to not have GA track localhost hits if you're actively developing. The other perk is you don't have to worry about messing with page:change or page:load bindings and that you can be confident that it'll work on any browser that's trackable by GA without having to worry about double hits or anything weird.

生产检查是可选的,但是如果您正在积极地开发,这是一种很好的方法来避免GA跟踪本地主机命中。另一个好处是,你不必担心弄乱页面:更改或页面:加载绑定,你可以确信它可以在GA可跟踪的任何浏览器上运行,而不必担心双击或任何奇怪的事情。

#4


6  

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

快速浏览一下源代码就会发现,这个gem所做的唯一一件事就是向资产管道中添加一些javascript

# 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.

这就是一切。您可以使用gem,也可以将类似代码片段手工添加到javascript资产中。

#5


3  

I appreciate scottwb's answer, but unfortunately it does not work with Rails 5. In Rails 5 Turbolinks events were renamed. The 'page:change' event was renamed to 'turbolinks:load'. This is why his example does not work anymore.

我很欣赏scottwb的回答,但不幸的是它不能在Rails 5上工作。在Rails 5 Turbolinks事件被重命名。“更改”事件被重命名为“turbolinks:load”。这就是他的例子不再适用的原因。

You can find an overview of how they were renamed here: https://github.com/turbolinks/turbolinks/blob/master/src/turbolinks/compatibility.coffee

您可以在这里找到如何重命名它们的概述:https://github.com/turbolinks/turbolinks/blob/master/src/turbolinks/compatibility.coffee。

Since this took me some time to figure out, I am posting the proper Rails 5 implementation for everybody coming after me.

因为这花了我一些时间去弄清楚,我正在发布正确的Rails 5实现,因为每个人都在跟踪我。

Put the following code in your <head>

将以下代码放在您的中

  <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', 'auto');
    //ga('send', 'pageview'); //moved to an asset file because of turbolinks
  </script>

And then in a js file (eg. application.js) in you asset pipeline:

然后在js文件中(如。在您的资产管道中:

$(document).on('turbolinks:load', function() {
   ga('send', 'pageview', window.location.pathname + window.location.search);
});

Remember to replace "UA-XXXXXXXX-X" with your Google Analytics ID.

记住用谷歌分析ID替换“ua - xxxxxx - x”。

#6


1  

This solution has worked the best for me: http://reed.github.io/turbolinks-compatibility/google_analytics.html.

这个解决方案最适合我:http://reed github.io/turbolinks-compatibility/google_analytics.html。

It requires at least Turbolinks v2.1.0 or greater.

它至少需要Turbolinks v2.1.0或更高版本。

#7


1  

We just took the standard snippet provided by Google, translated it to CoffeeScript, then modified the last action so it is bound to both the "ready" and "page:load" events. We also added conditional statement to only send the data if the current visitor is not at an admin (so our data remains as clean as possible).

我们只是使用谷歌提供的标准代码片段,将其翻译为CoffeeScript,然后修改最后的操作,使其同时绑定到“ready”和“page:load”事件。我们还添加了条件语句,只在当前访问者不在管理员的情况下发送数据(所以我们的数据保持尽可能干净)。

((i, s, o, g, r, a, m) ->
  i["GoogleAnalyticsObject"] = r
  i[r] = i[r] or ->
    (i[r].q = i[r].q or []).push arguments
    return

  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
  return
) window, document, "script", "//www.google-analytics.com/analytics.js", "ga"
ga "create", 'UA-XXXXXXXX-XX', "yourdomain.com"

$(document).on 'ready page:load', ->
  ga "send", "pageview", window.location.pathname unless $('body').data('admin') is true

#8


0  

According to this site, you only need to do a slight modification. The problem with Turbolinks is that it only updates parts of the website and therefore, Google Analytics often doesn't perceive that the page has changed. Thus, you must notify it manually by adding the following CoffeeScript to a file in your assets/javascript folder:

根据这个网站,你只需要做一个小小的修改。Turbolinks的问题是它只更新网站的部分内容,因此谷歌分析通常不会发现页面已经改变。因此,您必须通过将以下的CoffeeScript添加到您的资产/javascript文件夹中的文件中来手动通知它:

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

NOTE: this is not my code, it is taken directly from the previously linked website

注意:这不是我的代码,它直接取自之前链接的网站。

#1


13  

I think a better idea is to use the new Universal Analytics (from analytics.js file).

我认为更好的办法是使用新的通用分析(来自分析)。js文件)。

Universal Analytics Solution

通用的分析解决方案

  (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', "#{GA_UA}", "#{GA_URL}");
  ga('send', 'pageview');

And then when you wanna send an event for example, you can use

然后当你想发送一个事件的时候,你可以使用。

<script> ga('send', "event", "#{category}", "#{action}", "#{label}", "#{count}"); </script>

Be careful to render this code in the body, and not in the head. Turbo-links only replaces the body.

要小心在主体中而不是头部中呈现此代码。涡轮连杆只能代替车身。

And also be careful:

也要小心:

1) The GA_URL needs to match your pages's url

1) GA_URL需要匹配页面的url

2) The Events show up in real time, but in the events tab, they only appear after 24h +

2)事件实时显示,但在Events选项卡中,它们仅在24小时以上显示

3) Your account's property need to be 'Universal' for this solution to work

3)您的帐户的属性必须是“通用的”,才能使这个解决方案发挥作用

Universal Analytics docs:

通用分析文档:

https://support.google.com/analytics/answer/2790010?hl=en&ref_topic=2790009

https://support.google.com/analytics/answer/2790010?hl=en&ref_topic=2790009

#2


28  

I like vladCovaliov's solution because it seems most new accounts use Universal Analytics by default (which is also better featured in my opinion). However, I think this answer needs to be combined with the other suggestions that comment out the initial pageview, use the page:change event, and track pageviews, not events.

我喜欢vladCovaliov的解决方案,因为大多数新帐户默认使用通用分析(这在我看来也更有特色)。但是,我认为这个答案需要与其他建议结合起来,这些建议注释掉最初的pageview,使用page:change event,并跟踪pageviews,而不是events。

For example, in your <head>:

例如,在你的:

<% 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', 'auto');
    //ga('send', 'pageview');
  </script>
<% else %>
  <script>
    function ga () {
      var params = Array.prototype.slice.call(arguments, ga.length);
      console.log("GoogleAnalytics: " + params);
    };
  </script>
<% end %>

And then in a js file you have loaded through the asset pipeline:

然后在一个js文件中,通过资产管道加载:

$(document).on('page:change', function() {
  ga('send', 'pageview', window.location.pathname);
});

This will record a pageview for each page you load with or without Turbolinks. Note that the window.location.pathname is required, otherwise you can get the URL of the first page loaded for all the subsequent page loads. (This also gives you a nice place to edit the URL reported if you wanted to, say, strip out :id path segments from RESTful URLs.)

这将为您加载的每个页面或没有Turbolinks的页面记录一个页面视图。注意,window.location。路径名是必需的,否则您可以获得为所有后续页面加载而加载的第一个页面的URL。(这也为您提供了一个编辑报告的URL的好地方,例如,如果您想从RESTful URL中删除:id路径段。)

You can also then easily call:

你也可以很容易地打电话:

ga('send', "event", category, action, label, count);

To report Events for other interesting javascript events in your site.

为站点中其他有趣的javascript事件报告事件。

#3


14  

I've went with a different approach that I saw on some web site but it seems reasonable.

我采用了一种不同的方法,我在一些网站上看到过,但似乎是合理的。

Add GA to your header like usual but with a small modification of commenting out the trackPageview event from happening automatically.

像往常一样将GA添加到你的标题中,但是对trackPageview事件的注释做一个小修改。

<script type="text/javascript">
  var _gaq = _gaq || [];
  _gaq.push(['_setAccount', 'UA-FOOBAR']);
  //_gaq.push(['_trackPageview']);

  (function() {
    var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
    ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
  })();
</script>

Then add this somewhere in your body because the body gets reloaded for turbolinks.

然后把它添加到你身体的某个地方,因为你的身体会被重新装上松脂。

<% if Rails.env.production? %>
  <script>_gaq.push(['_trackPageview']);</script>
<% end %>

The production check is optional but this is a nice way to not have GA track localhost hits if you're actively developing. The other perk is you don't have to worry about messing with page:change or page:load bindings and that you can be confident that it'll work on any browser that's trackable by GA without having to worry about double hits or anything weird.

生产检查是可选的,但是如果您正在积极地开发,这是一种很好的方法来避免GA跟踪本地主机命中。另一个好处是,你不必担心弄乱页面:更改或页面:加载绑定,你可以确信它可以在GA可跟踪的任何浏览器上运行,而不必担心双击或任何奇怪的事情。

#4


6  

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

快速浏览一下源代码就会发现,这个gem所做的唯一一件事就是向资产管道中添加一些javascript

# 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.

这就是一切。您可以使用gem,也可以将类似代码片段手工添加到javascript资产中。

#5


3  

I appreciate scottwb's answer, but unfortunately it does not work with Rails 5. In Rails 5 Turbolinks events were renamed. The 'page:change' event was renamed to 'turbolinks:load'. This is why his example does not work anymore.

我很欣赏scottwb的回答,但不幸的是它不能在Rails 5上工作。在Rails 5 Turbolinks事件被重命名。“更改”事件被重命名为“turbolinks:load”。这就是他的例子不再适用的原因。

You can find an overview of how they were renamed here: https://github.com/turbolinks/turbolinks/blob/master/src/turbolinks/compatibility.coffee

您可以在这里找到如何重命名它们的概述:https://github.com/turbolinks/turbolinks/blob/master/src/turbolinks/compatibility.coffee。

Since this took me some time to figure out, I am posting the proper Rails 5 implementation for everybody coming after me.

因为这花了我一些时间去弄清楚,我正在发布正确的Rails 5实现,因为每个人都在跟踪我。

Put the following code in your <head>

将以下代码放在您的中

  <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', 'auto');
    //ga('send', 'pageview'); //moved to an asset file because of turbolinks
  </script>

And then in a js file (eg. application.js) in you asset pipeline:

然后在js文件中(如。在您的资产管道中:

$(document).on('turbolinks:load', function() {
   ga('send', 'pageview', window.location.pathname + window.location.search);
});

Remember to replace "UA-XXXXXXXX-X" with your Google Analytics ID.

记住用谷歌分析ID替换“ua - xxxxxx - x”。

#6


1  

This solution has worked the best for me: http://reed.github.io/turbolinks-compatibility/google_analytics.html.

这个解决方案最适合我:http://reed github.io/turbolinks-compatibility/google_analytics.html。

It requires at least Turbolinks v2.1.0 or greater.

它至少需要Turbolinks v2.1.0或更高版本。

#7


1  

We just took the standard snippet provided by Google, translated it to CoffeeScript, then modified the last action so it is bound to both the "ready" and "page:load" events. We also added conditional statement to only send the data if the current visitor is not at an admin (so our data remains as clean as possible).

我们只是使用谷歌提供的标准代码片段,将其翻译为CoffeeScript,然后修改最后的操作,使其同时绑定到“ready”和“page:load”事件。我们还添加了条件语句,只在当前访问者不在管理员的情况下发送数据(所以我们的数据保持尽可能干净)。

((i, s, o, g, r, a, m) ->
  i["GoogleAnalyticsObject"] = r
  i[r] = i[r] or ->
    (i[r].q = i[r].q or []).push arguments
    return

  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
  return
) window, document, "script", "//www.google-analytics.com/analytics.js", "ga"
ga "create", 'UA-XXXXXXXX-XX', "yourdomain.com"

$(document).on 'ready page:load', ->
  ga "send", "pageview", window.location.pathname unless $('body').data('admin') is true

#8


0  

According to this site, you only need to do a slight modification. The problem with Turbolinks is that it only updates parts of the website and therefore, Google Analytics often doesn't perceive that the page has changed. Thus, you must notify it manually by adding the following CoffeeScript to a file in your assets/javascript folder:

根据这个网站,你只需要做一个小小的修改。Turbolinks的问题是它只更新网站的部分内容,因此谷歌分析通常不会发现页面已经改变。因此,您必须通过将以下的CoffeeScript添加到您的资产/javascript文件夹中的文件中来手动通知它:

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

NOTE: this is not my code, it is taken directly from the previously linked website

注意:这不是我的代码,它直接取自之前链接的网站。