0

I have a chrome extension which should listen to localStorage changes in a content script on a given website.

Website sets local storage with window.localStorage.setItem('test', 'test');

I want to bind a listener to storage changes as

$(window).bind('storage', function (e) {
   alert('storage changed');
});

But, given code only works when I go to Chrome Inspect > Application > Local Storage and remove something or add.

I also tried to run a

var test = window.localStorage.setItem('test','test');

just below my binding still doesn't work.

How can I listen to localStorage changes in this case?

kritikaTalwar
  • 1,730
  • 1
  • 17
  • 25
  • `storage` event is not fired in the same document so it won't help you. You can try spoofing `localStorage` using DOM `Proxy` API inside a [script element (to make it run in page context)](https://stackoverflow.com/a/9517879). In addition to `setItem` you'll need to spoof `set` too. It's highly likely you can find an existing example, so do some googling. – wOxxOm Apr 19 '18 at 11:14
  • Create a function that generates a hash of localStorage contents and compares that with an earlier hash. Set timeout for a function to run every x ms.. this way you can see if storage has changed across sessions/tabs/windows – Eriks Klotins Apr 19 '18 at 11:21
  • @wOxxOm I mentioned that I tried to run it at same document, too. Why it doesn't work in that case? – Nuruddin Iminokhunov Apr 19 '18 at 11:23
  • Because that's how this event works as per the specification. – wOxxOm Apr 19 '18 at 11:27
  • @wOxxOm `$(window).bind('storage', function (e) { alert('storage changed'); }); var test = window.localStorage.setItem('test','test'); ` this code doesn't work, even at the same window, why it should work this way? if I am binding my storage to listen to events – Nuruddin Iminokhunov Apr 19 '18 at 11:29
  • Like I said, `storage` event won't help here. – wOxxOm Apr 19 '18 at 11:38

0 Answers0