can i be notified of cookie changes in client side javascript

One option is to write a function that periodically checks the cookie for changes:

var checkCookie = function() {

    var lastCookie = document.cookie; // 'static' memory between function calls

    return function() {

        var currentCookie = document.cookie;

        if (currentCookie != lastCookie) {

            // something useful like parse cookie, run a callback fn, etc.

            lastCookie = currentCookie; // store latest cookie

        }
    };
}();

window.setInterval(checkCookie, 100); // run every 100 ms
  • This example uses a closure for persistent memory. The outer function is executed immediately, returning the inner function, and creating a private scope.
  • window.setInterval

Leave a Comment