简体   繁体   English

清除 session 上的本地存储 clear

[英]Clear local storage on session clear

I want to clear localStorage on session clear, ie when the user exits the browser.我想清除 session 上的 localStorage,即当用户退出浏览器时。

I am using window.onbeforeunload for this purpose, as shown below.为此,我正在使用window.onbeforeunload ,如下所示。

window.onbeforeunload = function() {
    localStorage.removeItem('myToken');
    return '';
};

The problem is that this function also removes item also on browser reload.问题是这个 function 也会在浏览器重新加载时删除项目。

Is there any way around this, or is it any better way on implementing this?有没有办法解决这个问题,或者有没有更好的方法来实现这个?

Edit: This is a react app, is there any hook that prevents from clearing local storage on browser reload?编辑:这是一个反应应用程序,是否有任何钩子可以防止在浏览器重新加载时清除本地存储?

Use sessionStorage .使用sessionStorage It has the same methods as localStorage , but it clears when the session is cleared.它具有与localStorage相同的方法,但在清除 session 时会清除。

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

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