Google Analytics设置后立即检索Cookie的最佳方法是' _ga&#39 ;?我需要在数据库中本地保存cookie值。
示例代码:
<!-- 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>
可以使用 setTimeout 函数来检查cookie是否已设置但是有更好的方法可以使用事件吗?
答案 0 :(得分:0)
您无法在document.cookies
对象上添加直接事件。您可以编写自己的事件处理程序,这是一个定期搜索document.cookies中的更改的函数。根据此answer,我尝试使用带箭头的 ES6 语法重写cookieHandler
。你可以这样做:
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