解决方法
据我所知,不可能直接将更改(或类似)事件绑定到cookie.相反,我会采用这种方法:
创建一个轮询器,每隔X毫秒将cookie值与先前已知的值进行比较.
// 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!'); });
编辑:我现在测试了它,它的工作原理. See example