JavaScript: Automatically Logout from all Open Tabs When User Logout in One of them

In a web application, When the user opens the application in multiple tabs and then log out from one of them, Current tab refreshed and shows the Login page. But what about other open tabs? Open tabs still showing last opened page, because those tabs don’t know if User session terminated or not.

In this situation, Previously we have to call a refresh ajax call which is used to check the current user session. But that’s an unwanted call to the server, only to confirm Is user login or not?

Now forget about ajax call, Because In modern browsers, we have a “storage” event which can be used for sending a signal from one tab to another one. Means, we can attach a listener to a storage event (which fired on change of storage item) and on log out from one tab send a signal to other open tabs of the same application.

So, let’s start,

First, we have to attach a storage event, like

$(document).ready(function(){
  if (window.localStorage){
     $('a#_linkLogout').on('click', function(){
        localStorage.setItem("app-logout", 'logout' + Math.random());
        return true;
     });
  }
});

Now set a listener for same –

window.addEventListener('storage', function(event){
  if (event.key == "app-logout") {
    window.location = $('a#_linkLogout').attr('href');
  }
}, false);

That’s It.

110 thoughts on “JavaScript: Automatically Logout from all Open Tabs When User Logout in One of them

  1. I don’t even understand how I ended up here, but I believed this submit wasonce great. I do not know who you might be however certainly youare going to a famous blogger in the event you aren’t already.Cheers!

    Like

Leave a comment