Google Analytics Fix for Turbolinks - OpenDemocracyManitoba/winnipegelection GitHub Wiki
Rails 4 apps use Turbolinks by default. This means that links on the site don't trigger a full page load, instead AJAX is used to only refresh the <body>
contents.
Our Google Analytics Javascript is in the page <body>
, so each clicked link was being registered. However, the correct page path and title were not being set. For browsers that support Turbolinks the user's entry-page title/location/path were being re-used for every link visited.
Override the title
, location
and page
properties when sending a Google analytics pageview
event.
In the Google Analytics Javascript (found within the Application Layout), instead of:
ga('send', 'pageview');
We now do:
var page_location = location.href.split('#')[0];
var page_path = window.location.pathname;
ga('send', 'pageview', { "title": document.title,
"location": page_location,
"page": page_path});
This way the newly fetched title, location and path are correctly set both when visiting for the first time and when visiting a Turbolink.
Reference: Google Analytics Page Tracking Docs
I found a number of other fixes online that involved registering an event on the Turbolinks page:change
event to properly re-send the Google the pageview
. One such fix.
I'm able to get away with a much simpler fix since our Google Analytics Javascript is being re-run with every Turbolink fetched.