Rails 4 Turbolinks with Google Analytics

Rails 4 turbolinks with Google Analytics

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

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

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

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

Universal Analytics docs:

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

Google analytics with rails 4

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.

Adding Google Analytics to Rails 4.2 app

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.

Adding google analytics in rails without turbolinks

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.

Rails 4, Turbolinks, and Google Analytics - Tracking async modal clicks invalidates regular tracking

Well, after all that debugging, it seems that the precompiled assets weren't being updated on my production server for whatever reason. I'm not sure why they weren't being updated before, but after about 10 rake asset:clean and rake asset:precompile commands, the assets are now updated. Google Analytics is working great for all page views and modal clicks now!

Cant get google analytics working on rails project

I ran into an issue before with Rails 5 and Turbolinks and came across this issue for help.

It looks like you have things working with rack-tracker (based on ekremkaraca's comment). If you don't want to use a dependency you can set up Google Analytics with fairly minimal code using a partial and javascript snippet. I have a few apps configured this way:

app/assets/javascripts/google_analytics.js

document.addEventListener('turbolinks:load', function(event) {
if (typeof ga === 'function') {
ga('set', 'location', event.data.url);
ga('send', 'pageview');
}
});

app/views/layouts/_ga.html.haml (Using haml and not erb in this example)

:javascript
(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', 'YOUR_GA_CODE_HERE');

app/views/layouts/application.html.haml (Include the _ga partial in the head)

!!!
%html
%head
= stylesheet_link_tag 'application', media: 'all'
= javascript_include_tag 'application'

= render 'layouts/ga'
%body
= yield

app/assets/javascripts/application.js

...
//= require google_analytics

Unable to effectively use Google Tag Manager with Turbolinks

Replacing the tag will may all kinds of side effects (as you now realize, one being that the code is re-initialized and fires gtm.js events), so I suggest you drop the noscript part and move the rest to the head - I don't really know turbolinks (or RoR), but according to this article turbolinks will not reload the head.

Unfortunately there still might be side effects in an SPA since all items pushed to the dataLayer will just stay there. You might want to consider reseting the dataLayer when you load new content:

window.google_tag_manager[{{Container ID}}].dataLayer.reset();

Where {{Container ID}} is (obviously) the GTM-XXX id for your container. Don't just over the dataLayer variable with an uninitialized array (dataLayer = []) since GTM adds some methods to the dataLayer variable that will get lost if you overwrite it, and your GTM instance will stop to work.



Related Topics



Leave a reply



Submit