10

I need to update localStorage when document.cookie changes. Is there any way to set a listener, overwrite a prototype to act as middleware or some other pattern that would result in the ability to trigger a function on change? I'm trying to avoid something like polling on an interval.

Thanks for any ideas.

fancy
  • 48,619
  • 62
  • 153
  • 231
  • 3
    @dirkbonhomme The answer to that questions is to create a poller. This question specifically says `I'm trying to avoid something like polling on an interval.` – boom Feb 21 '12 at 09:58

2 Answers2

3

Theres no avoiding it, these events simply dont exist, you'll need to poll.

smassey
  • 5,875
  • 24
  • 37
  • 1
    Right now I'm setting all cookies in a custom way from my application allowing me to tie into those events. Just wanted to modulize it away to pure client-side. – fancy Feb 21 '12 at 15:31
  • Bummer, that's not what I wanted to hear smassey :P – GoldenNewby Feb 21 '12 at 19:06
-2

Try with cookies.onChanged

browser.cookies.onChanged.addListener(function(changeInfo) {
  console.log('Cookie changed: ' +
              '\n * Cookie: ' + JSON.stringify(changeInfo.cookie) +
              '\n * Cause: ' + changeInfo.cause +
              '\n * Removed: ' + changeInfo.removed);
});

Beware of browser compatibility.

https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/API/cookies/onChanged

Matteo Boscolo
  • 638
  • 2
  • 8
  • 18
  • 3
    This is part of the web extensions API (for browser extensions) and will not working in normal client side code. – andred Aug 28 '21 at 12:08
  • This code snippet is there on MDN's website and this is for browser extension and even this code doesn't work for Safari browsers. A solution based on polling will only work here. – wingman__7 Aug 09 '22 at 09:28