DEV Community

Igor Alexandrov
Igor Alexandrov

Posted on • Originally published at jetrockets.pro

Passing events between browser tabs without WebSockets

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);
  });
Enter fullscreen mode Exit fullscreen mode

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)