Jquery cookie监视器 [英] Jquery cookie monitor
本文介绍了Jquery cookie监视器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
当cookie被更改时,什么是最好的JS或JQuery特定方法来监控浏览器的网页生命周期中的Cookie生命周期?
What's the best JS or JQuery-specific approach to monitor a cookie through-out the page life on the browser and trigger an event, when the cookie is' changed?
推荐答案
据我所知,不可能直接将更改
(或类似)事件绑定到cookie。相反,我会采用这种方法:
As far as I know, it is not possible to bind a change
(or similar) event to a cookie directly. Instead, I would go for this approach:
创建一个轮询器,每隔X毫秒将Cookie值与之前已知的值进行比较。 p>
Create a poller that compares the cookie value to the previously known value every X milliseconds.
// basic functions from the excellent http://www.quirksmode.org/js/cookies.html
function readCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for(var i=0;i < ca.length;i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1,c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
}
return null;
}
/////////////////////////////////
// ACTUAL FUN STUFF BELOW
/////////////////////////////////
var cookieRegistry = [];
function listenCookieChange(cookieName, callback) {
setInterval(function() {
if (cookieRegistry[cookieName]) {
if (readCookie(cookieName) != cookieRegistry[cookieName]) {
// update registry so we dont get triggered again
cookieRegistry[cookieName] = readCookie(cookieName);
return callback();
}
} else {
cookieRegistry[cookieName] = readCookie(cookieName);
}
}, 100);
}
用法如下:
listenCookieChange('foo', function() {
alert('cookie foo has changed!');
});
注意:这没有经过测试,只是一个简短的演示问题。
Note: this has not been tested and is just a quick demo of how I would approach the problem.
这篇关于Jquery cookie监视器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文