在标签页/浏览器关闭时清除localStorage,但不刷新 [英] Clear localStorage on tab/browser close but not on refresh
问题描述
是否有办法检测标签关闭事件以清除 localStorage
。我需要 localStorage
来跨标签共享数据。 window.onbeforeunload
事件正常,但它对我有两个问题:
Is there a way to detect tab close event to clear the localStorage
. I need localStorage
to share data across tabs. window.onbeforeunload
event works fine but it has 2 issues for me:
- 它也刷新页面,我不想要。
- 我不需要关闭选项卡上的确认框。
- It also fires on page refresh which I dont want.
- I don't need confirm box on tab close.
清除 sessionStorage
。同时我可以清除 localStorage
但不知道要绑定什么事件。我检查了几个已经提供的问题,但似乎没有解决这个问题的方法,通过使用标记点击链接和表单提交,但没有一个干净的方法来解决这个问题。请为此提出任何解决方案。
Like when window is closed the sessionStorage
is cleared. At same time I can clear localStorage
but don't know what event to bind to. I checked a few questions already available but none seems to address this issue there are workarounds by using flags for click on links and form submits but not a clean way to do it. Kindly suggest any solution for this.
推荐答案
我能够找到解决方案并思考共享。
由于window.onbeforeunload事件在浏览器/选项卡关闭时触发,但在刷新时也是这样(我不想),事情是我的本地存储在rfresh时也被处理。我不想要的。为了克服这个问题,我实现了另外1个事件处理程序window.onload,它只在刷新时触发,而不在tab / browser关闭处,在那里我会重置localStorage,就像什么都没有发生过一样。代码是:
I was able to find solution to this and thought of sharing. Since the window.onbeforeunload event fires on browser/tab close but on refresh as well(which i did not want) the thing was my localstorage was being processed at time of rfresh as well. Which I did not want. In order to overcome this I implemented 1 more event handler window.onload that fires only on refresh and not on tab/browser close where I would reset the localStorage as if nothing had happened. The code is:
window.onbeforeunload = function (e) {
window.onunload = function () {
window.localStorage.isMySessionActive = "false";
}
return undefined;
};
window.onload = function () {
window.localStorage.isMySessionActive = "true";
};
我在window.onbeforeunload中返回undefined,因为我不想要在选项卡/浏览器上显示确认弹出窗口关闭并刷新。
I returned undefined in window.onbeforeunload as i did not want a confirm popup to appear on tab/browser close and refresh.
这篇关于在标签页/浏览器关闭时清除localStorage,但不刷新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!