我正在寻找一种方法来中断任何 localStorage 更改。我发现有一些神秘的条目,我不知道它们来自哪里,我希望调试器中断任何更改,以便我可以检查代码。这包括:
localStorage.someKey = someValue;
localStorage["someKey"] = someValue;
localStorage.setItem("someKey", someValue);
因为有很多方法可以改变/创建 localStorage 中的条目,简单地覆盖 .setItem
并执行 debugger;
是行不通的。任何想法表示赞赏。
最佳答案
不是在原生 localStorage
对象上,而是在代理版本上:
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);
};
}
})
});
我们创建一个 Proxy
对于将拦截 property assignment 的 window.localStorage
(处理 localStorage.someKey = someValue
和 localStorage["someKey"] = someValue
情况)和 property access (处理 localStorage.setItem("someKey", someValue)
案例)。
现在我们需要将 window.localStorage
指向我们的代理,但它是只读的。但是,它仍然是可配置的!我们可以用 Object.defineProperty
重新定义它的值.
关于javascript - 如何中断 localStorage 更改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49092423/