Barba: Google Analytics Issue

Created on 9 Nov 2016  路  9Comments  路  Source: barbajs/barba

Hi,
It's not clear how can I update Google Analytics.
I've my script added to every page:

How I have to do to fix it?
Thank you :)

Most helpful comment

I came up with this one, seems to work:

<script>
  window.dataLayer = window.dataLayer || [];
  function gtag(){dataLayer.push(arguments);}
  Barba.Dispatcher.on('initStateChange', function() {
    // modify to your needs
    var path = (window.location.href).replace(window.location.origin, '').toLowerCase();
    gtag('js', new Date());
    gtag('config', 'UA-XXXXXXX-1', {
      'anonymize_ip': true, // for GDPR
      'page_title' : document.title,
      'page_path': path
    });
  });
  </script>

If you have suggestions for improvements please let me know.

All 9 comments

Hello @SergioVento90

Something like this should do the job:

Barba.Dispatcher.on('initStateChange', function() {
  if (typeof ga === 'function') {
    ga('send', 'pageview', location.pathname);
  }
});

Oh really a fast answer :D
Should I include this string on Barbajs?

You have to include that code anywhere on your website after loaded Barba.js

Cheers

Perfect! Thank you

Does this mean that 2 page views are counted when you first go on the site as initStateChange is fired on first load?

@luruke, will the code example you provided

Barba.Dispatcher.on('initStateChange', function() {
  if (typeof ga === 'function') {
    ga('send', 'pageview', location.pathname);
  }
});

work with the new Google Analytics embed tag?

window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'UA-XXXXXXXX-1');

bigskillet: It doesn't appear to be working for me anymore either with the new GA embed.

I came up with this one, seems to work:

<script>
  window.dataLayer = window.dataLayer || [];
  function gtag(){dataLayer.push(arguments);}
  Barba.Dispatcher.on('initStateChange', function() {
    // modify to your needs
    var path = (window.location.href).replace(window.location.origin, '').toLowerCase();
    gtag('js', new Date());
    gtag('config', 'UA-XXXXXXX-1', {
      'anonymize_ip': true, // for GDPR
      'page_title' : document.title,
      'page_path': path
    });
  });
  </script>

If you have suggestions for improvements please let me know.

I feel like this issue should be linked to on the FAQ page under
"_How can I update Google Analytics (or any other tracking sytem)?_"

Was this page helpful?
0 / 5 - 0 ratings

Related issues

Mexikaner9 picture Mexikaner9  路  3Comments

S1SYPHOS picture S1SYPHOS  路  3Comments

shanewmurphy picture shanewmurphy  路  3Comments

luglio7 picture luglio7  路  4Comments

bobbyballard picture bobbyballard  路  3Comments