在关闭浏览器 javascript 时删除 localStorage

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18633715/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 12:40:52  来源:igfitidea点击:

Remove localStorage on closing browser javascript

javascriptjquerylocal-storage

提问by Nothing

I found most answer using window.onbeforeunloadto handle browser closing. But it also does action when refreshing browser. I just want to remove my localStorage when browser closed not refreshing.

我发现大多数答案window.onbeforeunload用于处理浏览器关闭。但它也会在刷新浏览器时执行操作。我只想在浏览器关闭而不刷新时删除我的 localStorage。

回答by Richard Dalton

You can use the sessionStorageobject instead of localStorage.

您可以使用sessionStorage对象而不是localStorage.

sessionStorageis cleared automatically when the browser is closed.

sessionStorage浏览器关闭时自动清除。

It works in pretty much the same way as localStorage:

它的工作方式与 localStorage 几乎相同:

sessionStorage.setItem("Test", "Test");

var item = sessionStorage.getItem("Test");

回答by Arun P Johny

I think what you are looking for is sessionStoragenot localStorage

我认为您正在寻找的是sessionStorage而不是localStorage

回答by Prostil Hardi

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.

如果您希望存储一些仅用于该特定会话的数据,例如用户登录,那么您需要使用 sessionStorage 但如果您的要求是您希望允许用户打开多个选项卡,那么 SessionStorage 将不起作用,因为 sessionStorage不跨选项卡共享,为此您需要使用 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.

请务必记录打开和关闭的选项卡数量,并在最后一个选项卡关闭时清除 localStorage。