Jquery cookie monitor

后端 未结 3 576
南方客
南方客 2020-12-15 11:02

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?

3条回答
  •  無奈伤痛
    2020-12-15 11:39

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

提交回复
热议问题