我在页面 A 中添加了一些本地存储中的值。当我转到页面 B 时,本地存储不应该被清除,但确实如此。这是一个程序错误。但是,我无法正确跟踪它以了解何时发生这种情况。
我尝试执行 setInterval 来每 1 秒在控制台中记录一次本地存储的值,但当我退出时,我会丢失我的值。
我想知道是否有一种方法或工具可以确定在什么时刻我像调用堆栈一样清除本地存储,而不是在 F12 开发工具中跟踪断点。我进行了搜索(CTRL + SHIFT + F)来查找 localStorage.clear()
,但在我的结果中,我清除 LS 的位置不相关且从未到达。
最佳答案
您可以尝试使用storage
事件。
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.
由于只有在同源的另一个页面中更改 Storage 对象时才会触发此事件,因此我们必须在 Page B 中添加事件监听器并更改 Page 中的 Storage 对象答:
由于文档在堆栈片段中沙箱化,我们必须使用 jsfiddle。
Page B
Page A
<小时/>如何运行示例:
- 打开两个页面。
- 转到页面 A 并运行 fiddle。
- 检查页面 B 结果。
首次运行后,您必须使用页面 A 中的 localStorage.setItem()
更改 Storage 键的任意值才能再次触发该事件。
关于javascript - 如何检测本地存储何时被清除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43747422/