我可以通知客户端javascript中的cookie更改 [英] can i be notified of cookie changes in client side javascript

查看:71
本文介绍了我可以通知客户端javascript中的cookie更改的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以在客户端javascript中以某种方式跟踪Cookie(对于我的域)的更改。例如,如果cookie被更改,删除或添加,则会调用一个函数

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

按优先顺序


  • 标准跨浏览器

  • 跨浏览器

  • 浏览器特定

  • 扩展/插件

  • standard cross browser
  • cross browser
  • browser specific
  • extension / plugin

为什么?因为我在窗口/标签#1中依赖的cookie可以在窗口/标签#2中更改。

Why? because cookies I depend on in window / tab #1 can get changed in window / tab #2.

我发现chrome允许扩展通知cookie更改。但那是我最不喜欢的选项

I found out that chrome allows extensions to be notified of cookies changes. But thats my least favorite option

推荐答案

一种选择是编写一个定期检查cookie变化的函数:

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




  • 此示例使用闭包来表示持久性内存。外部函数立即执行,返回内部函数,并创建一个私有范围。

  • window.setInterval

    • 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
    • 这篇关于我可以通知客户端javascript中的cookie更改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆