Below is a sample code that can be used to integrate the Google Analytics gtag method with Cookie Consent. Make sure you insert your UA id and the correct url of your Cookie Consent javascript.


This code will make sure that Google Analytics will not set any tracking cookie for the user until he has consented.


<script async src="https://www.googletagmanager.com/gtag/js?id=UA-XXXXXXX-XX"></script>
<script type="text/javascript">
// Insert your UA here
var gtagId = 'UA-XXXXXXX-XX';

// Disable tracking by default
window['ga-disable-' + gtagId] = true;

// Initialize gtag
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
</script>
<script src="https://cookie.consent.is/cc/xxxxxxxx.js"></script>
<script type="text/javascript">
window.addEventListener("load", function() {
window.cookieconsent.initialise({
  onInitialise: function(status) {
    if (this.hasConsented('analytics')) {
      // User has already allowed the analytics category

      // Enable tracking
      window['ga-disable-' + gtagId] = false;

      // Track this pageview
      gtag('config', gtagId);
    }
  },
  onAllow: function(category) {
    if (category == 'analytics') {
      // User just allowed the analytics category

      // Enable tracking
      window['ga-disable-' + gtagId] = false;

      // Track this pageview
      gtag('config', gtagId);
    }
  },
  onRevoke: function(category) {
    if (category == 'analytics') {
      // Prevent any further tracking for this session
      window['ga-disable-' + gtagId] = true;
    }
  }
})
});
</script>