google-analytics-turbolinks icon indicating copy to clipboard operation
google-analytics-turbolinks copied to clipboard

Doesn't work with gtag.js

Open soundasleep opened this issue 6 years ago • 1 comments

If you're using gtag.js, this gem won't work, because the pageview needs to send the analytics ID. I'm not sure if it's possible to add this functionality to this project.

https://developers.google.com/analytics/devguides/collection/gtagjs/pages

gtag('config', 'GA_TRACKING_ID', {
  'page_title' : 'homepage',
  'page_path': '/home'
});

soundasleep avatar Apr 17 '18 04:04 soundasleep

I solved this locally with a snippet like this:

if typeof Turbolinks != 'undefined' && Turbolinks.supported
  eventName = if typeof Turbolinks.controller != 'undefined' then 'turbolinks:load' else 'page:change'
  document.addEventListener eventName, (event) =>

    if window.gtag != undefined && window.GA_ID != undefined
      # gtag.js
      gtag('config', window.GA_ID, {
        'page_path': location.pathname,
        'page_title': document.title,
      })
    else if window.ga != undefined
      # Google Analytics
      ga('set', 'location', location.href.split('#')[0])
      ga('send', 'pageview', {"title": document.title})
    else if window._gaq != undefined
      _gaq.push(['_trackPageview'])
    else if window.pageTracker != undefined
      pageTracker._trackPageview();

and I set window.GA_ID when I initialise Google Analytics. This also means you can only have one GA property per page.

soundasleep avatar Apr 17 '18 04:04 soundasleep