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?
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:
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);
}
Usage would then be something like this:
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.
EDIT: I have tested this now and it works. See example :)
Know what, this helped for something weird. I was trying to use Google Translate (http://translate.google.com/translate_tools?hl=en) on a mobile webapp and everytime the language is changed, it kept inserting a bar at the top as the first child of document.body . I am now tracking the 'googtrans' cookie and doing this
listenCookieChange('googtrans', function() {
$(document.body).css('top','0px');
});
There is a jQuery
plugin for cookies
.
http://plugins.jquery.com/project/Cookie
It is not difficult to access the cookies in a html document, they live in document.cookie
.
<!-- Add cookie -->
$.cookie('cookieName':'cookieValue');
<!-- get cookie -->
$.cookie('cookieName');
<!-- removecookie -->
$.cookie('cookieName', null);
Additionally there are options arguments for add a cookie, e.g. expiry.
However in reply to your question, I don't actually think you can apply a event listener on to cookies unfortunately.
精彩评论