What if need to pass some event from one browser tab to each others? And we don't have WebSockets...
It turns out that localStorage raises events π
Namely, events are triggered when an item is added, deleted, or changed in another context. In essence, this means that when you change localStorage in one tab, other tabs can find out about this by listening to the storage event of the global window object. For example:
window.addEventListener('storage', function (event) {
console.log(event.key, event.newValue);
});
Of course, there are some restrictions on use (you can read about them here https://www.w3.org/TR/webstorage/), but for simple cases it is match perfect.
Top comments (0)