I am experiencing a strange issue in Safari (Version 13.1).
Use case: I am synchronizing data between various open tabs. This is implemented by writing to local storage and listening to the "storage" event.
According my understanding (and MDN: https://developer.mozilla.org/en-US/docs/Web/API/Window/storage_event), the storage event should be fired when something is written to local storage and two conditions are fulfilled:
- the value for the item has changed
- this change is originating from the same domain, but a different document (i.e. other tab/window)
In other words:
- Let's say I have two open tabs (A and B)
- Both listen for changes to "storage"
- One of the tabs (A) writes something to local storage
- Only the other tab (B) should receive the "storage" event
This works perfectly fine in Chrome, Firefox & Opera. But in Safari it is fired within the same tab as well.
This code will replicate this (works on any site in the console):
window.addEventListener('storage', event => console.log(event));
window.localStorage.setItem('foo', 'bar');
- In Chrome/Firefox/Opera nothing will be logged (expected behavior)
- In Safari, a storage event will be logged in the same window
In addition, the event itself does not seem to have sufficient information to identify which tab has triggered it. I am pondering to write another helper with a unique key per open tab and write that to local storage and listen for changes to it. But before I do that I wanted to see if I am missing something. I know there are some libraries to message other tabs, but I am reluctant to introduce a dedicated library for something as basic as this.
Question: Am I missing something? Is there a way to let the storage event in Safari only fire when something is written from other tabs?