简体   繁体   中英

How to clear local storage on browser close but not refresh?

My requirements are:

  1. Have to detect browser close event and it should not execute onpage refresh.

  2. If code works only on browser close then have to clear localstorage.

  3. Already i tried with onbeforeunload but it is executing on browser close event and page refresh event.

  4. So my code only works on browser close event not on page refresh (F5 or clicking on refresh symbol).

You cannot tell the difference between the browser being closed and the window/tab containing your page being refreshed. The information simply isn't available.

For your specific use case, it sounds like you might be able to use session storage rather than local storage. The point of session storage is that it expires when the user is done with the page. You can try that out with this example :

display("Existing <code>sessionStorage.foo</code>: " + sessionStorage.foo);
sessionStorage.foo = new Date().toISOString();
display("New value set: " + sessionStorage.foo);

For me on Firefox, Chrome, and IE9 (so presumably IE9+), refreshing doesn't clear session storage, but closing the tab does.

Alternately, you could set a timestamp in local storage when the page is being unloaded (from onbeforeunload ), and when you come back to the page in the future, if that timestamp is sufficiently out of date, clear the storage and start fresh. That doesn't clear the store when you leave the page, but does act as though it did when you come back after an interval.

There is no event that gets fired when only the browser is closed. The closest is the onbeforeunload event which gets emitted when the window is about to unload its resources.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM