javascript 如何在浏览器关闭但不刷新时清除本地存储?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25589804/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to clear local storage on browser close but not refresh?
提问by user3523448
My requirements are:
我的要求是:
Have to detect browser close event and it should not execute onpage refresh.
If code works only on browser close then have to clear localstorage.
Already i tried with onbeforeunload but it is executing on browser close event and page refresh event.
So my code only works on browser close event not on page refresh (F5 or clicking on refresh symbol).
必须检测浏览器关闭事件,它不应该执行页面刷新。
如果代码仅在浏览器关闭时工作,则必须清除 localstorage。
我已经尝试过 onbeforeunload 但它正在浏览器关闭事件和页面刷新事件上执行。
所以我的代码只适用于浏览器关闭事件而不适用于页面刷新(F5 或点击刷新符号)。
回答by T.J. Crowder
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 storagerather than local storage. The pointof 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.
对于 Firefox、Chrome 和 IE9(大概是 IE9+),刷新不会清除会话存储,但关闭选项卡会。
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 actas though it did when you come back after an interval.
或者,您可以在页面卸载时(从onbeforeunload
)在本地存储中设置时间戳,并且当您将来返回该页面时,如果该时间戳已经过时,请清除存储并重新开始。当您离开页面时,这不会清除商店,但确实会像您在一段时间后返回时一样。
回答by Miguel Mota
There is no event that gets fired when onlythe browser is closed. The closest is the onbeforeunloadevent which gets emitted when the window is about to unload its resources.
仅关闭浏览器时不会触发任何事件。最接近的是onbeforeunload事件,它在窗口即将卸载其资源时发出。