I am having a bit of difficulty implementing google analytics to my rails 4 project. I included the tracking code to the bottom of my layouts file and have even tried to remove turbolinks as suggested here however i google is still unable to detect this tracking cookie. Any ideas ?
I set up Google Analytics a few days before..
1.) The Turbolink Workaround
With Turbolinks, the Google Analytics JavaScript library is not sufficient to record a page visit for every page update.
The workaround should be loaded on every page and it can be included as an application-wide asset (it will load before Turbolinks).
Add the file app/assets/javascripts/analytics.js.coffee
to include the Turbolinks workaround:
app/assets/javascripts/analytics.js // Coffee $(document).on 'page:change', -> if window._gaq? _gaq.push ['_trackPageview'] else if window.pageTracker? pageTracker._trackPageview() // Javascript $(document).on('page:change', function() { if (window._gaq != null) { return _gaq.push(['_trackPageview']); } else if (window.pageTracker != null) { return pageTracker._trackPageview(); } });
2.) Create a Footer Partial
Just create a a Partial into app/views/layouts
-> _footer.html.erb
Then Call your Partial on your application.html.erb -> <%= render 'layouts/footer' %>
Insert into your Footer the Analytics Track Code:
<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-XXXXXXX-XX', 'herokuapp.com'); ga('send', 'pageview'); </script>
You must replace UA-XXXXXXX-XX with your tracking ID, and herokuapp.com with your Domain if you have any.
Here is code without using coffeescript:
app/assets/javascripts/analytics.js $(document).on('page:change', function() { if (window._gaq != null) { return _gaq.push(['_trackPageview']); } else if (window.pageTracker != null) { return pageTracker._trackPageview(); } });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With