Use localStorage for Tab Synchronization
07 March 2024
Updated: 07 March 2024
localStorage
localStorage is a method for persistent data storage in the browser. The storage itself is a simple key-value store with a synchronous API
We can write data to a given key using the following:
And we can get that data back using:
Pretty neat right?
For the purpose of this post we’ll look into how we can use this as a method for sending data between different browser tabs of the same website
Storage Event
Aside from just data storage - localStorage (as well as sessionStorage) provides us with a notification when the data in a storage is changed - this is called a StorageEvent
. What’s particularly interesting to us is that it’s fired in all other tabs of a particular site when any a tab of that site modifies the data
We can listen for this event using window.addEventListener
Now, if you think about it for a short while, you may come to an interesting conclusion - we can talk to other tabs
Speaking to Tabs
Open this page in two different windows side-by-side for this example
Since we can talk between tabs, we can synchronize parts of our UI using the messages we recieive
Below we have a button that uses this - each time it is pressed in one tab - it updates the count in all tabs
The code for this can be seen below:
Generic Implementation
So overall, this is a pretty neat method for sharing data between pages, but we end up having to do some repetitive work when setting this up in many places or when working with anything that isn’t a string (as you can see with the parseInt
s required in the above example)
To make this a little more generic we’re first going to extract the getting and setting of data into their own functions:
These provide relatively simple wrappers around the reading and writing of data and making it possible for us to work with objects
Next, we can provide an easy way to define a data reader and writer - the reason we define these separately is to make the interface a little easier for consumers to use without needing to rearrange all their code:
Our reader function will call the provided onChange
callback that is provided to it when the data is changed with the parsed data. We can implement the same button as above using this new code as can be seen below:
And for the the sake of being complete, we can see the refactored button running below: