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.
1 |
<script>localStorage.setItem('islogin','yes');</script> |
2) Change localStorage Item
When users log out from any tab. You need to change the localStorage value from “yes” to “no”.
1 |
<script>localStorage.setItem('islogin', 'no');</script> |
3) Set Storage Event Listener
When the localStorage item changed “storage” event fired automatically in all tabs.
1 2 3 4 5 6 7 8 |
<script> function storageChange (event) { if(event.key === 'islogin') { window.location.href = "index.php"; } } window.addEventListener('storage', storageChange, false) </script> |
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!
Thanks for your time, to know about me.
Hello I Am Vijay Poshiya. 🙂
Here’s My little description of your attention on Me and My blog. I am here to help you with PHP programming. I can give you a cake walkthrough platform where a complex program can make it easier for you. I will also provide you with the rare collections of task sets over the internet.
I hope you will find your solutions in better understanding shape within my blog.
You can read more about PHPAdvices at the “About” page.
Leave a Comment