如何中断localStorage更改 [英] How to break on localStorage changes
问题描述
我正在寻找一种打破所有localStorage更改的方法。我发现有一些神秘的条目,我不知道它们是从哪里来的,我希望调试器中断所有更改,以便检查代码。这包括:
I'm looking for a way to break on any localStorage changes. I have found that there are some mysterious entries that I have no idea where that is coming from and I would like the debugger to break on any changes so that I can inspect the code. This includes:
localStorage.someKey = someValue;
localStorage["someKey"] = someValue;
localStorage.setItem("someKey", someValue);
由于存在多种更改/创建localStorage条目的方法,因此只需覆盖 .setItem
并执行 debugger;
无效。知道了任何想法。
Since there are so many ways to alter/create an entry in localStorage, simply overriding .setItem
and do debugger;
will not work. Any idea is appreciated.
推荐答案
不在本地 localStorage
对象上,但是在代理版本上:
Not on the native localStorage
object, but on a proxied version:
Object.defineProperty(window, 'localStorage', {
configurable: true,
enumerable: true,
value: new Proxy(localStorage, {
set: function (ls, prop, value) {
console.log(`direct assignment: ${prop} = ${value}`);
debugger;
ls[prop] = value;
return true;
},
get: function(ls, prop) {
// The only property access we care about is setItem. We pass
// anything else back without complaint. But using the proxy
// fouls 'this', setting it to this {set: fn(), get: fn()}
// object.
if (prop !== 'setItem') {
if (typeof ls[prop] === 'function') {
return ls[prop].bind(ls);
} else {
return ls[prop];
}
}
// If you don't care about the key and value set, you can
// drop a debugger statement here and just
// "return ls[prop].bind(ls);"
// Otherwise, return a custom function that does the logging
// before calling setItem:
return (...args) => {
console.log(`setItem(${args.join()}) called`);
debugger;
ls.setItem.apply(ls, args);
};
}
})
});
我们创建了 代理
for window.localStorage
会拦截属性分配(处理 localStorage.someKey = someValue
和 localStorage [ someKey] = someValue
情况)和财产访问(处理 localStorage.setItem( someKey,someValue)
情况)。
We create a Proxy
for window.localStorage
that will intercept property assignment (handling the localStorage.someKey = someValue
and localStorage["someKey"] = someValue
cases) and property access (handling the localStorage.setItem("someKey", someValue)
case).
现在我们需要指出 window.localStorage
,但它是只读的。但是,它仍然可以配置!我们可以使用 Object.defineProperty
。
Now we need to point window.localStorage
at our proxy, but it's read-only. However, it's still configurable! We can redefine its value with Object.defineProperty
.
这篇关于如何中断localStorage更改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!