LoginSignup
7
4

More than 5 years have passed since last update.

Rails5(Turbolinks5)にGA(google analytics)を設置!

Posted at

はじめに

間違っているかもしれません。
挙動の確認は取れてますが、自己責任で使ってください。

Google Analyticsの設置

レイアウトに以下のコードを貼り付ける。

<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-000000-00', 'auto');
  ga('send', 'pageview');

</script>

ここまでは同じです。

turbolinks5で動くようにする。

ページ切り替えのイベントでGAへの送信が発火するようにします。

# Google Analyticsの設定
$ ->
  $(document).on 'turbolinks:render', ->
    if window.ga?
      ga('set', 'location', location.href.split('#')[0])
      ga('send', 'pageview')

多分動きます。
JavaScriptがOFFでも大丈夫です。

参考

Turbolinks 5とTurbolinks Classic(2.x)の比較

7
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
4