问题
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.
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.
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.
回答1:
You can try using the storage event.
The storage event is fired when a storage area (localStorage or sessionStorage) has been modified.
Example:
window.addEventListener('storage', function(e) {
//console.log(e.key, e.oldValue,e.newValue, e.url, e.storageArea);
});
Important:
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.
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.
Since the document is sandboxed in stack snippets, we'll have to use jsfiddle.
Page B
Page A
How to run the example:
- Open both pages.
- Go to Page A and run the fiddle.
- Check Page B result.
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.
来源:https://stackoverflow.com/questions/43747422/how-to-detect-when-local-storage-is-cleared