javascript 检测 localStorage 的任何变化?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22994774/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Detect any change in localStorage?
提问by Devashish
Is there any way to detect any change in HTML5 localStorage and then call certain functions if there is any change indeed? I have certain keys stored with names as "e1", "e2", "e3", and so on...
有没有办法检测 HTML5 localStorage 中的任何更改,然后在确实有任何更改时调用某些函数?我将某些键存储为名称为“e1”、“e2”、“e3”等...
i want to detect if any key is removed or added and then trigger some functions if there is any change...
我想检测是否删除或添加了任何键,然后在有任何更改时触发某些功能...
回答by nilfalse
According to specs Storage
interface emits storage
eventon global objects which it affects.
根据规范Storage
接口在它影响的全局对象上发出storage
事件。
So in your case you may just add handler
因此,在您的情况下,您可以添加处理程序
window.addEventListener("storage", function () {
// do your checks to detect
// changes in "e1", "e2" & "e3" here
}, false);
There is no need for jQuery
even.
jQuery
甚至没有必要。
回答by Mac
The localDataStorageinterface (a handy wrapper for the HTML5 localStorage API) conveniently fires change events on the same page/tab/window in which the storage event occurred. Disclaimer: I am the author of the interface.
该localDataStorage接口(用于HTML5的localStorage API一个方便的包装)方便地触发在同一页/标签/窗口,在其中发生了存储事件的更改事件。免责声明:我是界面的作者。