3

I'm facing this problem where I have two dashboards for two users, one is admin and the other is a merchant. The problem is when admin logs in and in the new tab a merchant logs in too. If I refresh the admin page I get a navbar that is meant for merchant and the rest of the page is of admin... I'm storing the token in localStorage.

Can anyone tell me how I can logout the previously logged in user, If a new user logs in in the on the same browser?

Haris
  • 83
  • 5
  • If two dashboards are under different domains, you can use cookies and share those cookies with different subdomains. Checkout https://stackoverflow.com/questions/18492576/share-cookies-between-subdomain-and-domain for more information – Shakya Peiris Jan 30 '23 at 07:57

4 Answers4

0

Instead using localStorage, you should use sessionStorage when you want the token to be unique to each tab/session and to be deleted when tab is closed for ex

Zsolt Balint
  • 767
  • 1
  • 6
0

If you need to log out in the other tabs it would help to pass the signal between multiple tabs you can use a local storage event.

Set a logout-event on the previous tabs

localStorage.setItem('logout-event', 'logout' + Math.random());

Every other tab will listen it with the the code below.

window.addEventListener('storage', function(event){
    if (event.key == 'logout-event') { 
        // your code here
    }
});

Simply put whenever a merchant logs in using a new tab follow the above procedure to logout any other user.

Malik Bagwala
  • 2,695
  • 7
  • 23
  • 38
0

U can use sessionStorage Instead of localStorage: look at this: https://hashnode.com/post/how-to-handle-multi-user-login-in-same-browser-cjbxct3yq06mk4cwty2bmpsn1

  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Feb 01 '23 at 09:43
0

If you ignore IE, I prefer using Broadcast Channel API instead of localStorage event

Init your broadcast channel and listen the event

const bc = new BroadcastChannel("your_channel_name")

bc.onmessage = (e) => {
  // Business logic here
  // data sent through the channel is available at e.data
}

When you want to trigger the event

bc.postMessage("your logout message");
Sang Dang
  • 422
  • 2
  • 5
  • 13