我的案例:localStorage键+值,当浏览器关闭时应该删除,而不是单个选项卡。

请看看我的代码,如果它是正确的和什么可以改进:

//创建localStorage key + value if (localStorage) { localStorage。myPageDataArr = { "name" => "Dan", "lastname" => "Bonny" }; } //当浏览器关闭时- psedocode $(窗口).unload(函数(){ localStorage。myPageDataArr = undefined; });


当前回答

应该这样做,而不是使用delete操作符:

localStorage.removeItem(key);

其他回答

有五种方法可供选择:

setItem():将键和值添加到localStorage getItem():通过键从localStorage检索值 removeItem():按键从localStorage中删除一个项 clear():清除所有localStorage key():传递一个数字来检索localStorage的第n个键

您可以使用clear(),该方法在调用时清除该域的所有记录的整个存储。它不接收任何参数。

window.localStorage.clear();

这是一个老问题,但上面的答案似乎都不完美。

如果您希望存储身份验证或任何敏感信息,这些信息仅在浏览器关闭时被销毁,那么您可以依赖sessionStorage和localStorage进行跨选项卡消息传递。

基本上,这个想法是:

You bootstrap from no previous tab opened, thus both your localStorage and sessionStorage are empty (if not, you can clear the localStorage). You'll have to register a message event listener on the localStorage. The user authenticate/create a sensitive info on this tab (or any other tab opened on your domain). You update the sessionStorage to store the sensitive information, and use the localStorage to store this information, then delete it (you don't care about timing here, since the event was queued when the data changed). Any other tab opened at that time will be called back on the message event, and will update their sessionStorage with the sensitive information. If the user open a new tab on your domain, its sessionStorage will be empty. The code will have to set a key in the localStorage (for exemple: req). Any(all) other tab will be called back in the message event, see that key, and can answer with the sensitive information from their sessionStorage (like in 3), if they have such.

请注意,此方案不依赖于窗口。Onbeforeunload事件是脆弱的(因为浏览器可以关闭/崩溃而不触发这些事件)。此外,敏感信息存储在localStorage上的时间非常短(因为您依赖于跨选项卡消息事件的transcients更改检测),因此此类敏感信息不太可能泄漏到用户的硬盘驱动器上。

下面是这个概念的演示:http://jsfiddle.net/oypdwxz7/2/

如果您希望在浏览器关闭时删除键,则应该使用sessionStorage。

试着用

$(window).unload(function(){
  localStorage.clear();
});

希望这对你有用

没有这样的方法来检测浏览器关闭,所以可能你不能在浏览器关闭时删除localStorage,但有另一种方法来处理你可以使用sessionCookies,因为它会在浏览器关闭后销毁。这是我在我的项目中实现的。