Syncing LocalStorage across multiple tabs
For a fun side project, I decided to create a Chrome Extension that turns your new tab into a Kanban Board using React + Redux. After using the extension myself, I quickly realized there was a problem I hadn’t considered. If you’ve opened up two tabs but only added tasks in tab A, you won’t see that data reflected in tab B. Luckily, we can solve this problem with vanilla javascript.
To sync data across multiple tabs you will need to take advantage of the storage
event. As per the docs, this event will only trigger when a window other than itself makes changes to local storage.
Listening in on the event is straightforward:
window.addEventListener('storage', (e) => {
console.log(`Key Changed: ${e.key}`);
console.log(`New Value: ${e.newValue}`);
});
After this, it’s up to you to decide how you want to handle the event. In my project, I was able to dispatch a redux action to update the store with the new data.
Simple, right? Well, hold on — If tab A updates local storage, tab B detects that event and updates the redux store which in turns updates local storage, won’t tab A pick up on the update event from tab B causing an infinite loop?
Nope! A quick look at the setItem
method in the local storage documentation tells us that:
If the given key does exist in the list, and its value is not equal to value, then it must have its value updated to value. If its previous value is equal to value, then the method must do nothing.
This means we can safely use this strategy to handle keeping our tabs up to date. However, if you want to sleep soundly at night and not be at the mercy of the implementation, it’s still a good precaution to check that the data has actually changed before firing off any events.