Web Storage
Coordinate tabs and handle failures
React to storage events, recognize last-write-wins conflicts, and keep the interface usable when a Web Storage write fails.
8 minute lesson
Two tabs can edit the same localStorage key. The API offers notification, not conflict resolution.
The storage event fires in other documents sharing the storage area. It does not fire in the tab that made the change. Use it to refresh replaceable preferences or warn about stale state.
window.addEventListener('storage', event => {
if (event.key === 'field-notes:theme' && event.newValue) {
document.documentElement.dataset.theme = event.newValue
}
})
A read followed by a write is not a transaction. Two tabs can both read an old value and overwrite each other. Keep shared updates simple or move structured concurrent state to IndexedDB or a server.
Storage access and writes can throw because of policy, quota, or environment constraints. Catch failures at the write boundary and let the user continue without pretending the value was saved.
Open two tabs and change the theme in each. Confirm which tab receives each event. Then force a failed write and make the interface show a clear non-persistent state.
Lesson completed