Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery cookie monitor

Tags:

jquery

cookies

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?

like image 977
Satish Avatar asked May 06 '11 08:05

Satish


1 Answers

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 :)

like image 60
Aron Rotteveel Avatar answered Sep 22 '22 16:09

Aron Rotteveel