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, How do I detect that all the 5 tabs are closed?

I really appreciate any help you can provide.

Madhan1021
  • 120
  • 2
  • 7
  • 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? – Madhan1021 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 – mchowdam 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 – Madhan1021 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. – Madhan1021 May 16 '22 at 08:45

1 Answers1

0

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
  • 2,344
  • 2
  • 22
  • 44
Phạm Vỹ
  • 103
  • 2
  • @Phạm Vỹ, How to implement counting of tab open, I searched a lot but I am not getting the right answer for it. – Madhan1021 May 19 '22 at 09:04