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 -
The solution I needed is -
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 -
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!!!
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);