144
Views
9
Comments
How to clear local storage when the tab or browser is close?
Application Type
Traditional Web, Mobile, Reactive

I want to clear the local storage when the tab or browser is directly closed.

2025-04-17 05-42-16
Ajit Kurane

Hi Sumant,

Did you try below javascript,

onbeforeunload = function() { localStorage. removeItem(key); return ''; }; 

Thanks.

2022-11-15 07-57-26
sumant kumar

Yes, but it is not working.


2022-12-09 04-50-17
Shubham Doshi

Hello Sumant,

If you want to clear the data so frequently, why are you saving data in the local storage. You can use Session storage. You need to add JS to implement this.

Kindly go through the below link, you will get the clear idea about it:

https://developer.mozilla.org/en-US/docs/Web/API/Window/sessionStorage


Hope it helps :)

2022-11-15 07-57-26
sumant kumar

No, actually I want to make the user log in again when he directly closes the tab or browser. FOr that, I want to clear the local storage.

2022-12-09 04-50-17
Shubham Doshi

Okay.

Correct me if I am wrong. So, you wan to logout the user when the tab or application is closed. And for that purpose you are clearing local storage?

2022-12-09 04-50-17
Shubham Doshi

Then you need to call logout action on "window.onbeforeunload" & "window.onunload" events.

You can refer the below link:

https://stackoverflow.com/questions/3888902/detect-browser-or-tab-closing


2022-11-15 07-57-26
sumant kumar
UserImage.jpg
Joe K Khaung

Let me hop on this wagon of Q&A. pls share the solution if anyone has found. My requirement is almost identical as sumant kumar. 

I like to capture the logout log in the database table only when browser closes. Not when tabs are closed. Rational is that user could open multiple tabs for same app, and it is not much convenient to users to re-login, everytime they close the tab. Thank.

Community GuidelinesBe kind and respectful, give credit to the original source of content, and search for duplicates before posting.