我可以通知客户端javascript中的cookie更改

pm1*_*100 15 javascript cookies

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

按优先顺序排列

  • 标准的跨浏览器
  • 跨浏览器
  • 浏览器特定
  • 扩展/插件

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

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

Ric*_*all 23

我们可以使用CookieStoreAPI​​:

cookieStore.addEventListener('change', ({changed}) => {
    for (const {name, value} of changed) {
        console.log(`${name} was set to ${value}`);
    }
});
Run Code Online (Sandbox Code Playgroud)

  • 这是理想的方式 - 但并非所有浏览器都完全支持 - https://caniuse.com/?search=cookie%20store%20api (12认同)

pai*_*lee 14

一种选择是编写一个定期检查cookie以进行更改的函数:

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
Run Code Online (Sandbox Code Playgroud)
  • 此示例使用闭包来执行持久性内存.外部函数立即执行,返回内部函数,并创建私有范围.
  • window.setInterval

  • 6年后-我想知道这是否仍然是唯一的方法。 (3认同)
  • @d7my `checkCookie` 在实例化时立即被调用并返回一个 fn,所以不,你不需要在 `setInterval` 中调用它 (3认同)
  • @Worthy7 这看起来像是浏览器扩展的 API,而不是网站 (2认同)

小智 8

我觉得我的方法更好。我编写了一个自定义事件来检测何时出现 cookie:

const cookieEvent = new CustomEvent("cookieChanged", {
  bubbles: true,
  detail: {
    cookieValue: document.cookie,
    checkChange: () => {
      if (cookieEvent.detail.cookieValue != document.cookie) {
        cookieEvent.detail.cookieValue = document.cookie;
        return 1;
      } else {
        return 0;
      }
    },
    listenCheckChange: () => {
      setInterval(function () {
        if (cookieEvent.detail.checkChange() == 1) {
          cookieEvent.detail.changed = true;
          //fire the event
          cookieEvent.target.dispatchEvent(cookieEvent);
        } else {
          cookieEvent.detail.changed = false;
        }
      }, 1000);
    },
    changed: false
  }
});

/*FIRE cookieEvent EVENT WHEN THE PAGE IS LOADED TO
 CHECK IF USER CHANGED THE COOKIE VALUE */

document.addEventListener("DOMContentLoaded", function (e) {
  e.target.dispatchEvent(cookieEvent);
});

document.addEventListener("cookieChanged", function (e) {
  e.detail.listenCheckChange();
  if(e.detail.changed === true ){
    /*YOUR CODE HERE FOR DO SOMETHING 
      WHEN USER CHANGED THE COOKIE VALUE */
  }
});
Run Code Online (Sandbox Code Playgroud)


Mos*_*e L 6

如果操作 cookie 的代码是您的,您可以使用它 localStorage来跟踪随事件变化的变化。例如,您可以在 localStorage 上存储垃圾以触发其他选项卡上的事件。

例如

var checkCookie = function() {

var lastCookies = document.cookie.split( ';' ).map( function( x ) { return x.trim().split( /(=)/ ); } ).reduce( function( a, b ) { 
        a[ b[ 0 ] ] = a[ b[ 0 ] ] ? a[ b[ 0 ] ] + ', ' + b.slice( 2 ).join( '' ) :  
        b.slice( 2 ).join( '' ); return a; }, {} );


return function() {

    var currentCookies =  document.cookie.split( ';' ).map( function( x ) { return x.trim().split( /(=)/ ); } ).reduce( function( a, b ) { 
        a[ b[ 0 ] ] = a[ b[ 0 ] ] ? a[ b[ 0 ] ] + ', ' + b.slice( 2 ).join( '' ) :  
        b.slice( 2 ).join( '' ); return a; }, {} );


    for(cookie in currentCookies) {
        if  ( currentCookies[cookie] != lastCookies[cookie] ) {
            console.log("--------")
            console.log(cookie+"="+lastCookies[cookie])
            console.log(cookie+"="+currentCookies[cookie])
        }

    }
    lastCookies = currentCookies;

};
}();
 $(window).on("storage",checkCookie); // via jQuery. can be used also with VanillaJS


// on the function changed the cookies

document.cookie = ....
window.localStorage["1"] = new Date().getTime(); // this will trigger the "storage" event in the other tabs.
Run Code Online (Sandbox Code Playgroud)

  • 这非常有趣 - 使用 localStorage 作为打开到同一个“应用程序”的浏览器窗口之间的通信机制 (3认同)

fuw*_*hin 6

方法一:定期轮询

轮询 document.cookie

function listenCookieChange(callback, interval = 1000) {
  let lastCookie = document.cookie;
  setInterval(()=> {
    let cookie = document.cookie;
    if (cookie !== lastCookie) {
      try {
        callback({oldValue: lastCookie, newValue: cookie});
      } finally {
        lastCookie = cookie;
      }
    }
  }, interval);
}
Run Code Online (Sandbox Code Playgroud)

用法

listenCookieChange(({oldValue, newValue})=> {
  console.log(`Cookie changed from "${oldValue}" to "${newValue}"`);
}, 1000);

document.cookie = 'a=1';
Run Code Online (Sandbox Code Playgroud)

方法二:API拦截

截距 document.cookie

(()=> {
  let lastCookie = document.cookie;
  // rename document.cookie to document._cookie, and redefine document.cookie
  const expando = '_cookie';
  let nativeCookieDesc = Object.getOwnPropertyDescriptor(Document.prototype, 'cookie');
  Object.defineProperty(Document.prototype, expando, nativeCookieDesc);
  Object.defineProperty(Document.prototype, 'cookie', {
    enumerable: true,
    configurable: true,
    get() {
      return this[expando];
    },
    set(value) {
      this[expando] = value;
      // check cookie change
      let cookie = this[expando];
      if (cookie !== lastCookie) {
        try {
          // dispatch cookie-change messages to other same-origin tabs/frames
          let detail = {oldValue: lastCookie, newValue: cookie};
          this.dispatchEvent(new CustomEvent('cookiechange', {
            detail: detail
          }));
          channel.postMessage(detail);
        } finally {
          lastCookie = cookie;
        }
      }
    }
  });
  // listen cookie-change messages from other same-origin tabs/frames
  const channel = new BroadcastChannel('cookie-channel');
  channel.onmessage = (e)=> {
    lastCookie = e.data.newValue;
    document.dispatchEvent(new CustomEvent('cookiechange', {
      detail: e.data
    }));
  };
})();
Run Code Online (Sandbox Code Playgroud)

用法

document.addEventListener('cookiechange', ({detail: {oldValue, newValue}})=> {
  console.log(`Cookie changed from "${oldValue}" to "${newValue}"`);
});

document.cookie = 'a=1';
Run Code Online (Sandbox Code Playgroud)

笔记

  1. 不适用于 IE
  2. 需要用于 Safari 的 BroadcastChannel polyfill

结论

| Metric \ Method  | Periodic Polling            | API Interception |
| ---------------- | --------------------------- | ---------------- |
| delay            | depends on polling interval | instant          |
| scope            | same-domain                 | same-origin      |
Run Code Online (Sandbox Code Playgroud)