Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)

like image 564
f.lorenzo Avatar asked Nov 17 '14 13:11

f.lorenzo


People also ask

Does localStorage work across tabs?

The main features of localStorage are: Shared between all tabs and windows from the same origin. The data does not expire. It remains after the browser restart and even OS reboot.

Why we should not use localStorage?

Limitations & considerations to use local storage: It is not secure, can be accessed by browser developer tools, so don't use it to store sensitive data. It can be cleared by the user when he/she clears all browser history. It can only store string data.

Is window localStorage synchronous?

LocalStorage is synchronous, each local storage operation you run will be one-at-a-time. For complex applications this is a big no-no as it'll slow down your app's runtime.


2 Answers

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);
}
like image 194
Roman Bekkiev Avatar answered Oct 14 '22 07:10

Roman Bekkiev


Updated above answer, as document.createEvent now is part of an old, deprecated API.

const originalSetItem = localStorage.setItem;

localStorage.setItem = function(key, value) {
  const event = new Event('itemInserted');

  event.value = value; // Optional..
  event.key = key; // Optional..

  document.dispatchEvent(event);

  originalSetItem.apply(this, arguments);
};

const localStorageSetHandler = function(e) {
  alert('localStorage.set("' + e.key + '", "' + e.value + '") was called');
};

document.addEventListener("itemInserted", localStorageSetHandler, false);

localStorage.setItem('foo', 'bar'); // Pops an alert

https://developer.mozilla.org/en-US/docs/Web/Guide/Events/Creating_and_triggering_events

like image 28
Amsvartner Avatar answered Oct 14 '22 07:10

Amsvartner