can i be notified of cookie changes in client side javascript

后端 未结 6 1149
梦毁少年i
梦毁少年i 2020-12-03 01:21

Can I somehow follow changes to cookies (for my domain) in my client side javascript. For example a function that gets called if a cookie gets changed , deleted or added

6条回答
  •  没有蜡笔的小新
    2020-12-03 02:05

    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

提交回复
热议问题