Skip to content
Advertisement

Listen for changes with localStorage on the same window

I want to listen for changes that are happening in the localStorage API on the same page (Not in multiple tabs like the spec says).

I am currently using this code:

var storageHandler = function () {
    alert('storage event 1');
  };

  window.addEventListener("storage", storageHandler, false);

localStorage.setItem('foo', 'bar');

Does anyone know a vanilla JavaScript way to listen to events on localStorage on one page (no jQuery)

Advertisement

Answer

Since JS is dynamical language just rewrite original functions.

var originalSetItem = localStorage.setItem; 
localStorage.setItem = function(){
    document.createEvent('Event').initEvent('itemInserted', true, true);
    originalSetItem.apply(this, arguments);
}
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement