如何检测何时清除本地存储 [英] How to detect when local storage is cleared
问题描述
我在页面A中添加了本地存储中的一些值.当我进入页面B时,不应清除本地存储,但是应该清除.这是一个程序错误.但是,我无法正确跟踪它以了解何时发生这种情况.
I have some values in the local storage added in page A. When I go page B the local storage should not be cleared, but it is. This is a programmatic error. However, I cannot track it correctly to know when this happens.
我尝试仅执行setInterval来每1秒登录一次本地存储的值,而当我退出时会丢失值.
I tried just doing a setInterval to log in the console the value of my local storage each 1 second and I lose my values when I navigate out.
我想知道是否有一种方法或工具可以确定在什么时候像清除调用堆栈一样,比清除F12开发工具中的断点更能清除本地存储.我进行了搜索(CTRL + SHIFT + F)以找到localStorage.clear()
,但是在我的结果中,我清除LS的位置不相关且从未到达.
I wonder if there is a way to detect or tool to determine in what moment I clear my local storage like a call stack more than tracing breakpoints in the F12 dev tools. I did a Search (CTRL + SHIFT + F) to find localStorage.clear()
but in my results the places that I clear the LS are not related and never reached.
推荐答案
您可以尝试使用 storage
事件.
You can try using the storage
event.
当存储区域(localStorage或 sessionStorage)已被修改.
The storage event is fired when a storage area (localStorage or sessionStorage) has been modified.
示例:
window.addEventListener('storage', function(e) {
//console.log(e.key, e.oldValue,e.newValue, e.url, e.storageArea);
});
重要提示:
这不适用于进行更改的同一页面-它是 确实是域中其他页面使用存储进行同步的一种方式 进行的任何更改.
This won't work on the same page that is making the changes — it is really a way for other pages on the domain using the storage to sync any changes that are made.
由于仅当在同一原点的另一个页面中更改存储对象时才会触发此事件,因此我们必须在页面B中添加事件侦听器并在页面中更改Storage对象答:
Since this event will only be triggered if the Storage object is changed in another page within the same origin, we'll have to add the event listener in Page B and change the Storage object in Page A.
由于该文档已放入堆栈摘要中,因此我们将不得不使用jsfiddle.
Since the document is sandboxed in stack snippets, we'll have to use jsfiddle.
- 打开两个页面.
- 转到A页并运行小提琴.
- 检查B页结果.
第一次运行它后,您必须使用页面A中的localStorage.setItem()
更改存储键的任何值才能再次触发该事件.
After running it for the first time, you'll have to change any value of a Storage key with localStorage.setItem()
in Page A to trigger the event again.
这篇关于如何检测何时清除本地存储的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!