chrome.storage.onChanged Listener Patterns
Use storage.onChanged as an MV3 event bus: filtering by area and key, avoiding echo loops when the writer also receives the event, and keeping popup, options page and service worker in step.
Table of Contents
You write one key from the options page and three things go wrong: the service worker wakes for a change it does not care about, the popup re-renders a field the user is still typing in, and the options page reacts to its own write. All three come from the same property — chrome.storage.onChanged is a broadcast to every context with a listener, including the one that made the change. This page is part of Chrome Storage API & Sync and covers the filtering and guard patterns that make the event usable as a real cross-context bus.
Root cause: one event, every listener, including the writer
onChanged fires once per set call, not once per key, and it is delivered to every extension context that has registered a listener — popup, options page, offscreen document, content scripts and the service worker. The callback receives a changes object keyed by the names that actually changed, each with oldValue and newValue, plus the areaName string. Nothing in the payload tells you who wrote it, which is why “did I cause this?” has to be answered by comparing values rather than by tracking authorship.
Step 1. Register the listener where it will survive
In the service worker the listener must be attached during the synchronous evaluation of the worker script. A storage change is one of the events that can wake an evicted worker, and if the registration happens after an await, the event that caused the wake is dispatched before your handler exists.
1// background.js — top level, no awaits above this line
2chrome.storage.onChanged.addListener((changes, areaName) => {
3 // Cheapest possible rejection first: wrong area.
4 if (areaName !== "sync") return;
5
6 // Then the keys we actually care about. Everything else is somebody else's business.
7 const relevant = ["pollMinutes", "blockedHosts"];
8 const touched = relevant.filter((key) => key in changes);
9 if (touched.length === 0) return;
10
11 (async () => {
12 if (changes.pollMinutes) await rescheduleAlarm(changes.pollMinutes.newValue);
13 if (changes.blockedHosts) await rebuildRules(changes.blockedHosts.newValue);
14 })();
15});
Execution context: Extension service worker. The listener body stays synchronous and defers the real work to an async function, exactly as with onMessage. Filtering on areaName before anything else matters more than it looks: a busy extension writing to storage.session on every tab update would otherwise wake this handler continuously. Firefox and Safari deliver the same two arguments under browser.storage.onChanged.
Step 2. Guard the writer against its own event
In a UI context the danger is the opposite: reacting to your own write while the user is mid-interaction. The robust guard is a value comparison rather than a flag, because a flag has to be cleared and any early return leaks it.
1// options.js
2const inputs = new Map([
3 ["pollMinutes", document.querySelector("#pollMinutes")],
4 ["theme", document.querySelector("#theme")],
5]);
6
7chrome.storage.onChanged.addListener((changes, areaName) => {
8 if (areaName !== "sync") return;
9
10 for (const [key, el] of inputs) {
11 const change = changes[key];
12 if (!change) continue;
13
14 const next = String(change.newValue ?? "");
15 // If the control already shows this value, the change came from us. Do nothing —
16 // no re-render, no cursor jump, no scroll reset.
17 if (el.value === next) continue;
18
19 el.value = next;
20 }
21});
Execution context: Options page or popup renderer. Comparing the rendered value with newValue handles both cases with one branch: an echo of our own write is a no-op, and a genuine change from another tab is applied. This is the same reasoning used in syncing options form state with chrome storage, where the debounce interval makes echoes especially likely.
Step 3. Coalesce bursts before acting on them
A handler that rebuilds declarative rules or reschedules an alarm should not do so five times because the user dragged a slider. Debounce inside the listener, keyed by what the work actually depends on.
1// background.js — collapse a burst of changes into one rebuild
2let rebuildTimer = null;
3
4function scheduleRebuild(hosts) {
5 clearTimeout(rebuildTimer);
6 // 250 ms is long enough to swallow a slider drag, short enough to feel immediate.
7 rebuildTimer = setTimeout(() => { void rebuildRules(hosts); }, 250);
8}
Execution context: Extension service worker. setTimeout is acceptable here precisely because the delay is sub-second — the worker cannot be evicted while a handler chain is still settling, and a lost timer after eviction only means the rebuild happens on the next change instead. For anything measured in minutes, use chrome.alarms instead, since a timer will not survive.
Step 4. Read the change payload defensively
Both oldValue and newValue are optional. A key being created has no old value; a key being removed has no new one. Destructuring them without a guard is the single most common runtime error in onChanged handlers, and it only surfaces the first time a user resets their settings.
1function valueOf(change, fallback) {
2 // "newValue" in change distinguishes a removal from a write of undefined.
3 return "newValue" in change ? change.newValue : fallback;
4}
5
6chrome.storage.onChanged.addListener((changes, areaName) => {
7 if (areaName !== "sync") return;
8 const change = changes.pollMinutes;
9 if (!change) return;
10
11 const minutes = valueOf(change, 30); // 30 is the shipped default
12 const previous = "oldValue" in change ? change.oldValue : null;
13 if (minutes === previous) return; // a write of an identical value still fires
14
15 void rescheduleAlarm(minutes);
16});
Execution context: Any context with a listener. Using the in operator rather than a truthiness check matters because false, 0 and the empty string are all legitimate stored values — change.newValue || fallback silently replaces every one of them with the default. A set call that writes the value already stored also fires the event, so the equality check against oldValue is what stops a no-op write from triggering real work.
Cross-browser variation
- Chrome 120+:
onChangedfires forsync,localandsession. There is also a per-area form,chrome.storage.sync.onChanged, which delivers onlychangesand noareaName. - Firefox 121+: identical semantics under
browser.storage.onChanged. Because the MV3 background context is an event page, a handler that relies on module-scope state appears to work here and fails in Chrome — test the eviction path in Chrome. - Safari 17+: delivers the same arguments but may coalesce rapid writes into a single callback with several keys in
changes. Handlers that assume one key per callback will silently skip work. - All engines:
oldValueis absent when a key is created, andnewValueis absent when a key is removed. Read both defensively.
Verification
- Open the options page in two tabs. Change a value in one; the other should update the single affected control and leave every other field, and the caret, untouched.
- In the service worker console, log
Object.keys(changes)and confirm it lists only the keys that changed, not the whole stored object. - Stop the service worker from the extensions page, then change a value from the options page. The worker should start and run the handler — proof the listener is registered synchronously.
- Remove a key with
chrome.storage.sync.removeand confirm your handler tolerates a change entry with nonewValue.
FAQ
Does onChanged fire in the context that made the write?
Yes, in every engine. There is no option to exclude the writer, which is why the value comparison in step 2 exists rather than a flag.
Is there one event per key or one per set call?
One per set call, with every changed key present in the changes object. A multi-key set is a single event — and a single write against the sync write-rate quota, which is why batching is worth doing.
Why does my handler not fire for storage.session changes?
Check areaName before dismissing it: session changes do fire, but only for contexts that can see that area. Content scripts cannot read storage.session unless the extension has set its access level to allow them.
Does a listener registered in a content script fire for every site?
It fires in every frame where that content script is running and has registered, which is every matching tab at once. On a busy setting that means dozens of simultaneous handler invocations, so filter by key aggressively and keep the work per invocation trivial — anything expensive belongs in the service worker, which receives the same event once.
Can I tell which context made the change?
No. The payload carries no origin information. If you genuinely need it, write an author field alongside the value and read it in the handler — but a value comparison is usually the simpler answer.
Related
- Migrating storage schema between versions — reacting to shape changes, not just value changes.
- chrome.storage.session vs local — which area a key belongs in before you listen to it.
- Handling storage quota exceeded errors — why batched writes matter.
- Chrome Storage API & Sync — the guide this page belongs to.