Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding google analytics in rails without turbolinks

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

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?

like image 346
Sohail Aslam Avatar asked Sep 11 '26 01:09

Sohail Aslam


1 Answers

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

Then in a layout file:

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

Its simple and it works with/without Turbolinks.

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

like image 114
Dan Avatar answered Sep 12 '26 14:09

Dan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!