简体   繁体   English

如何仅在浏览器关闭时清除 localStorage

[英]How to clear localStorage only on browser close

I have a localStorage key (mykey) and want to remove this key only when the browser is closed.我有一个localStorage密钥(mykey),并且只想在浏览器关闭时删除此密钥。 It should not be cleared when the page is refreshed.刷新页面时不应清除它。

I have this Javascript code to clear the key on browser close.我有这个 Javascript 代码来清除浏览器关闭时的密钥。

window.onbeforeunload = function (event) {
    if (event && event.type == "beforeunload") {
        localStorage.removeItem("mykey");        
    }
};

This code is clearing the localStorage key on browser close and page refresh also.此代码也在浏览器关闭和页面刷新时清除localStorage键。 If I comment the code, then it works fine.如果我评论代码,那么它工作正常。 The key is not cleared on page refresh but only on browser close.该键在页面刷新时不会被清除,而只会在浏览器关闭时被清除。

I have observed that when the page is refreshed, the key will be cleared and then the debugger is hit for the window.onbeforeunload method.我观察到,当页面刷新时,密钥将被清除,然后调试器会针对 window.onbeforeunload 方法命中。

There is no other place where I'm removing the key.我没有其他地方可以移除钥匙。

UPDATE: I have replaced localStorage with sessionStorage at all places of get set for this key, but it's still the same.更新:我已经在所有设置这个键的地方用sessionStorage替换了localStorage ,但它仍然是一样的。

What you basically try to achieve is simply done by sessionStorage object.您基本上尝试实现的目标只是由sessionStorage object 完成。 You can use sessionStorage instead.您可以改用sessionStorage

localStorage is for data persistance with a different purpose to make sure data stays in the Browser Storage for long. localStorage用于数据持久性,具有不同的目的,以确保数据在浏览器存储中保留很长时间。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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