Dante1021
Dante1021

Reputation: 374

Clear tokens in Local Storage when all tabs or Browser is closed in React

I want to remove the user Authentication when the application has been loaded in multiple tabs. Once all the tabs that had the application loaded are closed or the entire browser is closed, I want to remove the token stored in local storage. When a user again opens a new tab and tries to enter the application, it should redirect to the login page. How can this be achieved in react, like how to detect that all tabs that have that application loaded closed?

Note -- I want to remove the token and display the login page only when all the tabs are closed or the browser is closed.

For an Instance, If the application has been loaded in 5 tabs, on the closing of all 5 tabs only I need to remove the token.

Is it possible to use a Broadcast channel to achieve this? but I am not sure how to implement them

Upvotes: 1

Views: 1988

Answers (1)

Phạm Vỹ
Phạm Vỹ

Reputation: 130

Did you try this way?

  1. Count every tab open and save it to localStorage
  2. Handle event unload and update localStorage if openedTab === 0 then clear it in unload event

Upvotes: 1

Related Questions