1

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

Dante1021
  • 304
  • 7
  • 20
  • 3
    Maybe you need to use `sessionStorage` instead of `localStorage`? – evolutionxbox May 16 '22 at 07:15
  • @evolutionxbox That would be my suggestion as well, but sessionStorage isn't shared between multiple tabs of the same page, so it probably wont be enough for this particular use case. – Nikolaj Dam Larsen May 16 '22 at 07:18
  • @NikolajDamLarsen Yes bud, that's why I need to use local storage, is there any possible way to implement this? – Dante1021 May 16 '22 at 07:20
  • Hope this one helps you https://stackoverflow.com/questions/23759555/remove-clear-local-storage-when-all-tabs-are-closed – mc-user May 16 '22 at 07:21
  • @mchowdam, appreciate for sharing it, but the problem is in most cases they have provided for a single tab closing, but my need is when multiple tabs that have the application loaded are getting close – Dante1021 May 16 '22 at 07:26
  • I have a workaround but not a good solution, we can explore more. We have a cookie/local storage variable which indicates that a tab is opened, all tabs set this variable by `setInterval` of very short duration, whenever a tab is closed or App is unmounted we can reset this variable, and `clearInterval` after clearing it if it is set again then another tab is opened so don't logout else if the variable is not set after clearing then this is the last tab setting it so the user can be logged out. – Shivam Sharma May 16 '22 at 08:00
  • @ShivamSharma, could you please elaborate more, sorry I am a newbie to javascript., so I can understand better. – Dante1021 May 16 '22 at 08:45

1 Answers1

1

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
Roman Mahotskyi
  • 4,576
  • 5
  • 35
  • 68
Phạm Vỹ
  • 130
  • 2