How to run Google Analytics code when cookies are accepted?


can someone let me know how to run the Google Analytics tracking code when someone accepts the cookies?

Here is the JS code for the cookie banner I created:

let cookieModal = document.querySelector('.cookie-consent-modal');
let cancelCookieBtn = document.querySelector('.btn.cancel');
let acceptCookieBtn = document.querySelector('.btn.accept');

cancelCookieBtn.addEventListener('click', function () {

acceptCookieBtn.addEventListener('click', function () {
  localStorage.setItem('cookieAccepted', 'yes');

setTimeout(function () {
  let cookieAccepted = localStorage.getItem('cookieAccepted');
  if (cookieAccepted != 'yes') {
}, 2000);

The Cookie Banners works just fine, but now I need to add the Google Analytics tracking code when cookies get accepted.

I guess I need to save it in the local storage, right?

  localStorage.setItem('cookieAccepted', 'yes');

Can I just make an if statement and code something like, if accepted run the Google Analytic code which looks something like this:

<!-- Global site tag (gtag.js) - Google Analytics -->
<script async src=""></script>
  window.dataLayer = window.dataLayer || [];
  function gtag(){dataLayer.push(arguments);}
  gtag('js', new Date());

  gtag('config', 'G-CYZ7731P2S');

Can someone please let me know how to connect this code with my cookie banner?

Thanks a lot for help!! :slight_smile:

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.