Middle
How to synchronize two browser tabs using localStorage? Talk about the storage event.
sobes.tech AI
Answer from AI
To synchronize two browser tabs using localStorage, the storage event is used. It triggers in other tabs when data in localStorage is changed in one tab.
Example usage:
// Add an event listener in both tabs
window.addEventListener('storage', (event) => {
if (event.key === 'syncKey') {
console.log('Data changed:', event.newValue);
// You can update state or perform necessary actions here
}
});
// Update localStorage in one of the tabs
localStorage.setItem('syncKey', JSON.stringify({ time: Date.now() }));
Features:
- The
storageevent does not fire in the same tab where the change occurred, only in other tabs. - It can be used for message passing between tabs, updating UI, or synchronizing state.
event.keyis the key that was changed.event.newValueandevent.oldValueare the new and old values.
Thus, storage is a simple and effective way for cross-tab communication without using servers or WebSocket.