The badge went 1, 2, 3, then 1. No exception, no reload, no second installation. The counter was a module-level let in the service worker, and the service worker had been terminated between clicks.
This is the smallest possible MV3 bug, which makes it a good place to see the three levels of fix.
The short version
- The counter lives in the worker's heap; the heap is disposable.
- Write it to
chrome.storage.sessionon every change for correctness. - Debounce the write if the counter changes rapidly, and accept a small loss window.
The one-line diagnosis
Add a boot marker:
console.log('boot', crypto.randomUUID(), new Date().toISOString()); If the marker appears between two clicks, the worker restarted. That is not a bug in your counter; it is the platform working as designed.
Fix A: write on every change
The simplest correct version:
let counter = 0; const KEY = 'counter'; async function init() { const stored = await chrome.storage.session.get(KEY); counter = (stored[KEY] as number | undefined) ?? 0; } async function increment() { counter++; await chrome.storage.session.set({ [KEY]: counter }); await chrome.action.setBadgeText({ text: String(counter) }); } This is durable against worker death, simple to reason about, and fine for a counter that changes a few times per minute. The cost is one storage write per click, which is negligible at human speed.
Fix B: debounce the write
If the counter changes in bursts — scroll events, message batches, a timer tick — writing every time is wasteful. Coalesce:
let flushHandle: ReturnType<typeof setTimeout> | undefined; function scheduleFlush() { if (flushHandle) return; flushHandle = setTimeout(async () => { flushHandle = undefined; await chrome.storage.session.set({ counter }); }, 500); } The trade-off is explicit: up to 500 milliseconds of increments can be lost if the worker dies. For a badge that is acceptable; for a quota counter it is not. Choose the window based on what a lost update costs, not on what feels fast.
Fix C: let the build handle it
If the counter participates in a larger state object, manual writes multiply. vite-mv3-sw-compile-persist marks top-level variables dirty after mutation, flushes them on a debounce and restores them before listeners run. The source stays a normal let:
let counter = 0; chrome.action.onClicked.addListener(() => { counter++; void chrome.action.setBadgeText({ text: String(counter) }); }); The config controls the area and the flush interval:
mv3Persistent({ backgroundEntry: /background\/index\.ts$/, stateStrategy: 'proxy', storageArea: 'session', autoFlushMs: 2_000, }); Two honest caveats. The flush is debounced, so the same loss window exists — autoFlushMs is a product decision. And the plugin cannot persist destructured bindings or anonymous callbacks that capture locals, so a counter declared as let { count } = … is not covered.
Which fix belongs in your extension
| Situation | Fix |
|---|---|
| One counter, human-speed clicks | A |
| Bursty updates, loss is tolerable | B |
| Many variables, existing code | C |
| Counter must survive browser restart | A or C with storageArea: 'local' |
That last row matters more than it looks. chrome.storage.session is cleared when the browser closes. A "lifetime total" counter belongs in local; a "this session" counter belongs in session. Using the wrong bucket produces a second bug that looks like the first.
What not to do
Do not keep the counter in memory and sync it "on idle". There is no idle callback you can rely on before termination. Do not use a beforeunload handler; service workers do not get one. And do not add a keepalive loop for a counter — the fix is three lines of storage, not twenty seconds of battery.
The verification
Click five times, open chrome://serviceworker-internals, stop the worker, click once more. The badge should read 6, not 1. Then restart the browser and check whether the expected value is 6 (local) or 0 (session) — both are correct, but only one matches your product intent.
Storage writes are asynchronous and batched by the browser, but they are not free. A counter that changes on every scroll event can produce hundreds of writes per minute, which is why Fix B exists. Measure with the performance panel if you are unsure; the profile is cheaper than the rewrite.
With and without the plugin
The before/after from the plugin's README is the whole argument:
Without vite-mv3-sw-compile-persist
let count = 0; chrome.action.onClicked.addListener(async () => { const stored = await chrome.storage.session.get('count'); count = (stored.count as number) ?? 0; count++; await chrome.storage.session.set({ count }); }); chrome.alarms.create('cleanup', { delayInMinutes: 5 }); chrome.alarms.onAlarm.addListener((alarm) => { if (alarm.name === 'cleanup') cleanup(); }); With vite-mv3-sw-compile-persist
let count = 0; chrome.action.onClicked.addListener(() => { count++; }); setTimeout(cleanup, 5 * 60_000); The second version is the code you meant to write. The plugin adds restore, dirty tracking, a debounced flush and alarm-backed timers at build time — no runtime import, no wrapper API.
Repository: vite-mv3-sw-compile-persist
If your counter just reset again while reading this, a star is a fair price for the fix.
Is your counter a session stat or a lifetime stat? The storage bucket follows from that answer.
