1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
|
// Save original methods
Storage.prototype._setItem = Storage.prototype.setItem;
Storage.prototype._getItem = Storage.prototype.getItem;
Storage.prototype._removeItem = Storage.prototype.removeItem;
Storage.prototype._clear = Storage.prototype.clear;
// Override setItem
Storage.prototype.setItem = function (key, value) {
const oldValue = this._getItem(key);
this._setItem(key, value);
const evt = new CustomEvent("storagechange", {
detail: {
type: "set",
key: key,
newValue: value,
oldValue: oldValue,
},
});
window.dispatchEvent(evt);
};
// Override getItem
Storage.prototype.getItem = function (key) {
const value = this._getItem(key);
const evt = new CustomEvent("storagechange", {
detail: {
type: "get",
key: key,
value: value,
},
});
window.dispatchEvent(evt);
return value;
};
// Override removeItem
Storage.prototype.removeItem = function (key) {
const oldValue = this._getItem(key);
this._removeItem(key);
const evt = new CustomEvent("storagechange", {
detail: {
type: "remove",
key: key,
oldValue: oldValue,
},
});
window.dispatchEvent(evt);
};
// Override clear
Storage.prototype.clear = function () {
this._clear();
const evt = new CustomEvent("storagechange", {
detail: {
type: "clear",
},
});
window.dispatchEvent(evt);
};
// Listen for events
window.addEventListener("storagechange", (e) => {
console.log("LocalStorage changed:", e.detail);
});
|