Syncing LocalStorage across multiple tabs

Image for post
Image for post

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:

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:

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.

Written by

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store