Nothing
Nothing

Reputation: 2642

Remove localStorage on closing browser javascript

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.

Upvotes: 6

Views: 18461

Answers (3)

Prostil Hardi
Prostil Hardi

Reputation: 61

If you are looking to store some data that you will be using only for that particular session say user login then you need to use sessionStorage but if your requirement is that you want to allow the user to open multiple tabs then SessionStorage will not work because sessionStorage is not shared across tabs, for this you will need to use localStorage.

Be sure to keep a count of the number of tabs opened and closed and clear the localStorage when the last tab is closed.

Upvotes: 4

Arun P Johny
Arun P Johny

Reputation: 388336

I think what you are looking for is sessionStorage not localStorage

Upvotes: 3

Richard Dalton
Richard Dalton

Reputation: 35793

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");

Upvotes: 20

Related Questions