0

What is the best way to retrieve cookie right after the Google Analytics set it '_ga'? I need to save cookie value locally in the database.

Sample code:

<!-- Global site tag (gtag.js) - Google Analytics -->
<script async src="https://www.googletagmanager.com/gtag/js?id=UA-281681-2"></script>
<script>
  window.dataLayer = window.dataLayer || [];
  function gtag(){dataLayer.push(arguments);}
  gtag('js', new Date());
gtag('config', 'UA-TRACKING-ID');

// retrieve _ga cookie:
  function getCookie(name){
    var matches = document.cookie.match(new RegExp(
      "(?:^|; )" + name.replace(/([\.$?*|{}\(\)\[\]\\\/\+^])/g, '\\$1') + "=([^;]*)"
    ));
    return matches ? decodeURIComponent(matches[1]) : undefined;
  }
  var cidLong = getCookie('_ga');
  var cid="NA";
  if (cidLong) {
   var tmp = cidLong.split('.');
   cid = tmp[2] + '.' + tmp[3];
  }
  // Will return 'NA' if _ga cookie is set first time
  console.log("cid: "+cid);

</script>

It is possible to use setTimeout function to check if the cookie is set but is there a better way like using events?

J.T
  • 270
  • 2
  • 9

1 Answers1

0

There is no direct event you can add on the document.cookies object. You can write your own event handler, a function that periodically searches for a change in the document.cookies. Based on this answer, I tried to rewrite the cookieHandler using ES6 syntax with arrow. You can proceed this way:

var lastCookie = document.cookie;

var cookieHandler = () => {
  var currentCookie = document.cookie; 

  if(  currentCookie !== lastCookie){
    console.log("something changed")
    lastCookie = currentCookie
  }
}

setInterval(cookieHandler, 1000); // the function is run after each 1s
edkeveked
  • 17,989
  • 10
  • 55
  • 93