A technical blog on Computer Science and Software Development topics by Tomás Pérez.

Local storage and the onstorage event

Every browser that supports local storage, exposes a new event in the window object called storage, so you can attach callbacks to it and be notified of changes.

This is great, and you can use now cool features like communication between multiple tabs of your browser, just setting values on it:

But there are several restrictions about the onstorage event, that you need to be aware if you want to use it as a way of communication:

  • The event change is only emitted when the values actually change. As you know local storage is a type of dictionary, so if you just change an element to have the exact same value than before it won't be triggered.
  • e.g. Suppose that you set an item called 'connected', if you just set its value to true, and it was true before, you won't receive the event. If you need to be notified, add a timestamp or random value, to the content of the message. Another option, if that's feasible, is to clear all the items with `localStorage.clear()` after you read every message, although the performance might be affected.

  • The notification is only received in a different context. That means different page, don't expect to communicate using local storage in the context of different objects in the same page. Some browsers will consider 'same page' to be applied to different iframes inside the current page. Chrome and Firefox seems to behave as expected and you can communicate between different iframes in the same page, but for that better use post messages whenever possible.
  • If you change `document.domain`, you won't receive any notification afterwards. It makes sense, as local storage is specific for domain and subdomain, so you can't read the local storage of `` from ``. If you have a page where you do the trick of changing `document.domain` to access to the parent frame, for instance, take into account that you won't be able to communicate using local storage.