简体   繁体   English

JavaScript浏览器关闭事件

[英]Javascript browser close event

Hi I have used localStorage to store the value of a variable.The problem is that localStorage never resets from what I managed to find on the internet.I am interested to reset localStorage when the browser is closed. 嗨,我使用localStorage来存储变量的值。问题是localStorage永远不会从我设法在互联网上找到的内容进行重置。我有兴趣在关闭浏览器时重置localStorage。

Is there a way to do that? 有没有办法做到这一点?

I have tryed using $(window).unload from jQuery but that detects changes related to the window and it resets the localStorage variable to soon. 我试过使用$(window).unload从jQuery,但它检测到与窗口相关的更改,并将localStorage变量重置为很快。

Read my answer in which I explained how to detect browser close, $(window).unload doesn't work always. 阅读我的答案 ,其中我解释了如何检测浏览器是否关闭,$(window).unload并不总是有效。

<script>
 window.onbeforeunload = function (e) {

 if (localStorage) {
    localStorage.clear();
 }
 };
</script>

But, yes I would recommend to use Cookies or session variable which would be destroyed on browser close instead of localStorage. 但是,是的,我建议您使用Cookies会话变量 ,该变量将在浏览器关闭时被破坏,而不是localStorage。

You probably want to use window.sessionStorage instead. 您可能想改用window.sessionStorage

sessionStorage 的sessionStorage

This is a global object (sessionStorage) that maintains a storage area that's available for the duration of the page session. 这是一个全局对象(sessionStorage),用于维护在页面会话期间可用的存储区域。 A page session lasts for as long as the browser is open and survives over page reloads and restores. 页面会话的持续时间只要浏览器处于打开状态,并且在页面重新加载和还原后仍然存在。 Opening a page in a new tab or window will cause a new session to be initiated. 在新标签或窗口中打开页面将导致启动新会话。

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

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