How to share Session storage data with other opened browser tabs in React

3.6k Views Asked by At

Here I have a part of a code, in which I needed to log in to the application, and I am storing the token in both local and session storage so that it can handle during the beforeunload event, storing in session will help during refresh and local to share data with multiple tabs so that I don't have to log in each time when opening a new tab.

But the problem I am facing is -

  • When I sign in to the application and if I open a new tab on loading of the new tab I can see the application gets logged in, but when I refresh it goes back to log in page, as I checked there is no token in session storage, so while refreshing the page it is logging out.

The solution I needed is -

  • How to get the data from session storage of the signed-in tab and send them across to all newly opened tabs, I have seen something like we can storage events or Broadcast API but I really don't know how to implement them in react and where to implement in this code

Code

useEffect(() => {
window.addEventListener("beforeunload",() => {
localStorage.removeItem("token")
let loggedIn = localStorage.getItem('token');
let sessionLoggedIn = sessionStorage.getItem('token');
if(!loggedIn) {
    if(sessionLoggedIn) {
        localStorage.setItem('token', JSON.parse(sessionLoggedIn));
        //go to authenticated space
        window.location.href = '/authenticated';
    } else {
        //go to login
        window.location.href = '/login';
    }
} else {
    //go to authenticated space
    window.location.href = '/authenticated';
}
})
})

While Signing in - I am storing the token with the value of random strings in both local and session storage when the user logs in to the application.

My complete requirement is -

  • After a user logs in to the site in any tab if they navigate to the site in a new tab they must already be logged in
  • When a user logs out of any tab they must log out of all tabs immediately
  • A user can refresh the page and stay logged in
  • Once all tabs are closed the user is logged out and must log back in

If any other implementation to replace this method also is much appreciable

Can someone guide me on how to achieve my requirement, Thanks a million!!!

1

There are 1 best solutions below

2
On

Both the localStorage and sessionStorage objects are from the current origin. Every tab of a browser is from a different origin(unless they are browsing the same site) and the session/local storage objects are going to be unique to these tabs.

However, if both the tabs run scripts that are controlled by you, it is possible to share the storage data between tabs using an API like BroadcastChannel.

var bc = new BroadcastChannel('share_storage');
bc.postMessage(window.sessionStorage);