Unmounted Function / Detect browser close

Hi everyone. I need to remove item from localstorage when browser close. Therefore, I use unmounted method. But I do not want to run my function when page refresh. Unmounted function runs also, when the page is refreshed .However I want to run my function only when browser close. How should I solve this?

There is no client-side JS API available to webpages for detecting when the web browser is closed. As far as I know, the best you can do is to listen for the unload event, but there are no guarantees it will be called, and when it’s called you don’t know if it’s because the user closed the tab, the browser, or navigates to another page.

Thank you very very much. But still I do not know how to solve this. Because unload event trigger when page refresh too. How can I detect page close with unload. Or how to remove item from localstorage when browser close ?

I don’t think you can detect the user leaves the page and don’t intent to come back to if for a while. You can detect when the user leaves the page with the unload event, but you have no way of knowing if the user intends to come back within 10 seconds or not.

But what is it that you store in localStorage that you need to remove? Maybe there is another way to do what you want.

Because I need to detect when browser first upload. Onload event or mounted methods also run refresh page. I want to run function once. So I used localstroge item to detect when browser open.
What is the correct way to do this? I want to show one time specific notification when user opens the page.

Then when you show the notification, store a value in localStorage indicating that you have showed it. And when the page loads, check if the value is stored in localStorage or not, and if it isn’t then show the notification. Why do you need something to run when the user leaves the page?

1 Like

Instead of localstorage I stored in session and it worked. Thanks a lot.