Wednesday, March 2, 2016

SignOut from all opened tabs when SignOut from one window using Javascript LocalStorage events

It is one of the very important requirements in the web application development. Assume, you are opening an application in multiple browser tabs. When you do sign out in one window the authentication session will be cleared and gets signed out in that window. But all other opened window also should sign out automatically without any direct browser interaction. To do that,

keep the user's logged in state in a browser's LocalStorage. update it when you logged in or logged out. Utilize the LocalStorage events to track the status and do a refresh.

But How..? you can do it using Timer. But using local storage events it can be done without any client-side overhead. The below code will do that for you.
Initialize the below LocalStorage 'storage' event listener in the application's common load method.
window.addEventListener('storage', this.storageChange, false);

When you first Sign In, update the local storage variable isLoggedIn value to 'true'
localStorage.setItem('isLoggedIn', true);

when you sign out update the local storage variable isLoggedIn value to 'false'

and the callback method will have the logic to refresh the page based on the condition. That is, it will keep on checking the isLoggedIn value is 'false'  whenever you update the LocalStorage.
function storageChange(event) {

    if (event.key == 'isLoggedIn' && event.newValue == 'false') {

        window.location.reload();

    }

},

No comments:

Post a Comment