Trigger an action when document.cookie changes?
Asked Answered
C

2

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.

Chamaeleon answered 21/2, 2012 at 8:55 Comment(1)
@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.Dulci
K
3

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

Kaluga answered 21/2, 2012 at 14:34 Comment(2)
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.Chamaeleon
Bummer, that's not what I wanted to hear smassey :PNegative
L
-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

Lichenin answered 15/1, 2021 at 15:54 Comment(2)
This is part of the web extensions API (for browser extensions) and will not working in normal client side code.Milline
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.Prochora

© 2022 - 2024 — McMap. All rights reserved.