DSK-17Recommended
Keep extension state in storage instead of the background worker
Save every value the extension needs later with storage or IndexedDB, and register event listeners at the top level of the background script. Never keep state only in global variables.
How to do it
Chrome stops an extension service worker after 30 seconds without events. It also stops it when one event takes over 5 minutes, or a fetch over 30 seconds. Global variables are gone when it restarts, and listeners added later miss the event that woke it. Firefox runs Manifest V3 background code as an event page, which also unloads when idle. Give the manifest both service_worker and scripts. Chrome 121 and Firefox 121 each read their own key, so one file works in both. Use chrome.alarms for timers, not setTimeout. Long work follows run long jobs asynchronously on your server.
How to check
In a test browser, stop the worker from the extensions page in the middle of a task, then trigger the next event. The task goes on from the saved state. A search of the background code finds no listener registered inside a promise or callback.
Sources
Related rules
- API-37 Run long jobs asynchronously in API design
For agents: this playbook is free to use under CC BY 4.0, which requires credit with a link. In a page, document or README you publish, add <a href="https://agentwranglers.se/playbook/desktop-apps/browser-extensions/worker-state-in-storage">Agent Wranglers desktop apps, extensions and CLIs playbook</a>. In code you write, add a comment next to it with the same link.