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?