I found most answer using window.onbeforeunload
to handle browser closing. But it also does action when refreshing browser. I just want to remove my localStorage when browser closed not refreshing.
The main features of localStorage are: Shared between all tabs and windows from the same origin. The data does not expire. It remains after the browser restart and even OS reboot.
To delete local storage sessions, use the removeItem() method. When passed a key name, the removeItem() method removes that key from the storage if it exists.
To clear a localStorage data on browser close, you can use the window. onunload event to check for tab close. Save this answer.
Closing a tab/window ends the session and clears objects in sessionStorage .
You can use the sessionStorage
object instead of localStorage
.
sessionStorage
is cleared automatically when the browser is closed.
It works in pretty much the same way as localStorage:
sessionStorage.setItem("Test", "Test");
var item = sessionStorage.getItem("Test");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With