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);
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.
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);
};
}
})
});
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).
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With