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

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

In this article, You will learn how to automatically logout from all open tabs when users log out in any tab using JavaScript in PHP.

When the user opens the same website in multiple tabs and then log out from one of them, the user will be logout from the current tab and show the login page. but what about other open tabs? Other open tabs still show the last opened page, because those tabs don’t know if the User session terminated or not.

In this case, We can frequently call an ajax call which is checking the current user session. This is useful just in case you want to maintain opened tabs in different browsers. But those ajax calls load to your server.

Now you can forget about the ajax call, Because Now a day in modern browsers, We have a localStorage which can be used to store some data to identify the user is logged in or not when a user log out from one tab send a signal to other open tabs of the same web application.

So, let’s go,

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

1) Set Item

In my example when a user login to the website, I have called localStorage setItem to set a key “islogin” and the value is “yes”. localStorage saves a token as a key and value. It has no expiry time. It will available when we open a new tab too.

2) Change localStorage Item

When users log out from any tab. You need to change the localStorage value from “yes” to “no”.

3) Set Storage Event Listener

When the localStorage item changed “storage” event fired automatically in all tabs.

Today, we learned about How to Automatically Logout From All Open Tabs When User Logout In Any Tab Using JavaScript In PHP.

I hope it helped you. Please let us know in the comment section if you have any concerns.

Thank You!