Automatically Logout From All Open Tabs When User Logout In Any Tab Using JavaScript

In this blog, you will learn how to automatically log out from all open tabs when the user logout in any tab using javascript.

On websites, When the users open the websites in multiple tabs and then log out from any of them, the active tab refreshed and shows the login page. But the rest tabs are remaining the same, Right?. But now we have a browser “storage” event that can send a signal from one tab to other tabs.

Let’s create a click event for the logout button. it will set localstorge in other words attach storage events.

$(document).ready(function () {
            if (window.localStorage) {
                $('#btnLog').on('click', function () {
                    localStorage.setItem("event-logout", 'logout-' + Math.random());
                    window.location = '/Account/Logout';
                    return true;
                });
            }
});

set listener for same

window.addEventListener('storage', function (event) {
            if (event.key == "event-logout") {
                window.location = '/Account/Logout';
            }
        }, false);

And that’s it.

I hope you guys found something useful. Please give your valuable feedback/comments/questions about this article. Please let me know how you like and understand this article and how I could improve it.

Submit a Comment

Your email address will not be published. Required fields are marked *

Subscribe

Select Categories