0

How to create handler on localestorage changed using native javascript?

My try is:

console.log("START");

window.addEventListener('storage',function(e){
   if(e.storageArea===sessionStorage){
        console.log("storage was changed");
   } else {
     /* else, event is caused by an update to localStorage, ignore it */
     console.log("ELSE");
   }

});

localStorage.setItem('qweyxcadsadsadsa', "DSADAS");

console.log("end")

But, it not working, where is a problem?

Thank you for any help!

There is a jsfiddle:

https://jsfiddle.net/1qft6gcb/

  • 1
    Possible duplicate of [How to bind to localStorage change event using jQuery for all browsers?](https://stackoverflow.com/questions/4671852/how-to-bind-to-localstorage-change-event-using-jquery-for-all-browsers) – lewis Jul 30 '17 at 12:39
  • @Lewis42 What? Where is answer to my question why it is not working? –  Jul 30 '17 at 12:42
  • 1
    "In other words, a storage event is fired on every window/tab except for the one that updated the localStorage object and caused the event." – lewis Jul 30 '17 at 12:43
  • SHIT, my answer was about javascript and its duplicate of answer about jquery? Really? Amazing –  Jul 30 '17 at 12:49
  • You could argue it is not a duplicate. But I think that question does have the answer you are looking for? – lewis Jul 30 '17 at 12:51
  • 1
    The other answer explains why javascript works that way. It just happens to be that the OP was using jQuery. Either way it doesn't matter as the general javascript behavior is documented in the answer. – pinkfloydx33 Jul 30 '17 at 13:14

1 Answers1

0

You can create your own trigger with setInterval(). On first run, store current values. After that, compare current values with previous, trigger if necessary and update values. I would suggest using an existing pub/sub library for that. Amplify.js encapsulates both local storage and pubsub, but is quite old -mainly because it works very well and doesn't need updates.

jotaelesalinas
  • 1,387
  • 1
  • 11
  • 24