Sharing Local Storage Between Tabs
Recently I have been working on an application that needed to be able to update the authentication token when logging in to another tab. This solution came about when a customer had multiple unsaved edits in one tab when their token expired. The question is, how do we enable this when tabs have different scopes?
Turns out the local storage API gives us a way to share state between tabs through the storage event.
All that is required is to listen for this event and check if the key we are interested in has changed.
For example, to listen to changes to the authToken key you can do the following:
window.addEventListener('storage', (event) => {
if (event.key === 'authToken') {
const newToken = event.newValue;
// Update your application with the new token
}
});
It is a pretty simple solution that just works. However, there is one thing to keep in mind when using this approach,
and that is that the storage event is only fired in other tabs, not in the tab that made the change. This is simple enough
to deal with as you are in the context of that window already, so do any updates you need as you go.
An example
You can see this at work here through the use of the popup below. Open the below popup (or tab through the link) and enter some text, and this tab will show what you have written below. All of this is done through your browser and does not require any server interaction at all.
Your endered text will appear below live as you type
Some other ideas
Animating between tabs
Here is a clunky demo of some animation between tabs using local storage. It isn’t perfect - just some green dots firing between tabs, but it is a fun idea to explore.
Select a tab and move your mouse around - you should see dots appear in the other tab following your mouse movements.
Note: This will only work on a desktop. You will also need to enable popups.
Sharing filters between tabs
This may be useful when you have multiple tabs open to the same application and want to keep the filters in sync. Enabling dashboards to share filter state between tabs could be a useful way to keep context when working across multiple screens.
Want to read more? Check out more posts below!