Detecting localStorage Changes on the Same Page
2025-05-20 08:18
TOC
本篇中文版:監聽 localStorage 事件:如何在同一頁面內偵測變更
Problem We’re Trying to Solve
Sometimes, we store information in the browser using mechanisms like Cookies, Local Storage, or IndexedDB.
By default, the native storage
event for Local Storage is designed to work across tabs or windows:
1window.addEventListener("storage", () => {});
But what if we want to detect changes within the same page? In that case, we need to manually override the localStorage
methods.
Listen in: Key takeaways from Google’s NotebookLM.
Listening for localStorage Events
We can override methods like setItem
on Storage.prototype
, and use CustomEvent to trigger our own change events.
1// Save original methods
2Storage.prototype._setItem = Storage.prototype.setItem;
3Storage.prototype._getItem = Storage.prototype.getItem;
4Storage.prototype._removeItem = Storage.prototype.removeItem;
5Storage.prototype._clear = Storage.prototype.clear;
6
7// Override setItem
8Storage.prototype.setItem = function (key, value) {
9 const oldValue = this._getItem(key);
10 this._setItem(key, value);
11
12 const evt = new CustomEvent("storagechange", {
13 detail: {
14 type: "set",
15 key: key,
16 newValue: value,
17 oldValue: oldValue,
18 },
19 });
20 window.dispatchEvent(evt);
21};
22
23// Override getItem
24Storage.prototype.getItem = function (key) {
25 const value = this._getItem(key);
26
27 const evt = new CustomEvent("storagechange", {
28 detail: {
29 type: "get",
30 key: key,
31 value: value,
32 },
33 });
34 window.dispatchEvent(evt);
35
36 return value;
37};
38
39// Override removeItem
40Storage.prototype.removeItem = function (key) {
41 const oldValue = this._getItem(key);
42 this._removeItem(key);
43
44 const evt = new CustomEvent("storagechange", {
45 detail: {
46 type: "remove",
47 key: key,
48 oldValue: oldValue,
49 },
50 });
51 window.dispatchEvent(evt);
52};
53
54// Override clear
55Storage.prototype.clear = function () {
56 this._clear();
57
58 const evt = new CustomEvent("storagechange", {
59 detail: {
60 type: "clear",
61 },
62 });
63 window.dispatchEvent(evt);
64};
65
66// Listen for events
67window.addEventListener("storagechange", (e) => {
68 console.log("LocalStorage changed:", e.detail);
69});
Translated by ChatGPT.