Menu

Why Your Extension's Counter Resets to Zero
πŸ“°

Why Your Extension's Counter Resets to Zero

DEV Community: javascriptΒ·DmitryΒ·9 days ago
#2RRQlpup
#devtojavascript#devto#dev#counter#chrome
Long article (1053 words) β€” no AI summary yet.
Reading 0:00
15s threshold

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.session on 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 ());

Enter fullscreen mode

Exit fullscreen mode

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 .…

Continue reading β€” create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.