这个问题的答案对我不起作用。我得到了Uncaught TypeError: Illegal invocation,所以我编写了自己的代码,该代码适用于大多数环境。它使用Proxy,更安全。
Storage.prototype.setItem = new Proxy(Storage.prototype.setItem, {
apply(target, thisArg, argumentList) {
const event = new CustomEvent('localstorage', {
detail: {
key: argumentList[0],
oldValue: thisArg.getItem(argumentList[0]),
newValue: argumentList[1],
},
});
window.dispatchEvent(event);
return Reflect.apply(target, thisArg, argumentList);
},
});
Storage.prototype.removeItem = new Proxy(Storage.prototype.removeItem, {
apply(target, thisArg, argumentList) {
const event = new CustomEvent('localstorage', {
detail: {
key: argumentList[0],
},
});
window.dispatchEvent(event);
return Reflect.apply(target, thisArg, argumentList);
},
});
Storage.prototype.clear = new Proxy(Storage.prototype.clear, {
apply(target, thisArg, argumentList) {
const event = new CustomEvent('localstorage', {
detail: {
key: '__all__',
},
});
window.dispatchEvent(event);
return Reflect.apply(target, thisArg, argumentList);
},
});