← ClaudeAtlas

chrome-ext-service-workerlisted

This skill should be used when working with Chrome extension service workers or background scripts. Trigger when: "service worker lifecycle", "background script", "extension service worker", "chrome.alarms", "offscreen document", "service worker restart", "top-level listener", "service worker idle", "event listener registration", "chrome.offscreen", "service worker termination", "state rehydration", "persistent background", "MV3 background", "service worker wake-up", "keepalive", "setTimeout in service worker".
RadOrigin-LLC/RAD-Claude-Skills · ★ 5 · Code & Development · score 73
Install: claude install-skill RadOrigin-LLC/RAD-Claude-Skills
# Chrome Extension Service Workers MV3 replaced persistent background pages with ephemeral, event-driven service workers. They wake to process events and terminate after ~30 seconds of inactivity. All in-memory state is lost on termination. Code must be structured around this fundamental constraint. ## The Ephemeral Lifecycle ``` [Event occurs] → [Worker starts] → [Script executes top-to-bottom] → [Registered listeners fire] → [~30s idle] → [Worker terminates] → [All global variables lost] ``` Every handler must assume zero prior state. Rehydrate from storage at the start of every event. ## Hard Rules ### 1. Register Listeners Synchronously at Top Level The browser scans for listeners on the first turn of the event loop. Listeners inside promises, callbacks, `setTimeout`, or `async` functions will NOT be registered in time. ```typescript // CORRECT — synchronous, top-level export default defineBackground(() => { chrome.runtime.onMessage.addListener(handleMessage); chrome.alarms.onAlarm.addListener(handleAlarm); chrome.runtime.onInstalled.addListener(handleInstall); }); // WRONG — async, buried inside callback export default defineBackground(async () => { await someSetup(); // TOO LATE — worker may have already handled the event chrome.runtime.onMessage.addListener(handleMessage); }); ``` ### 2. Never Use setTimeout/setInterval Standard timers are canceled on termination. Replace with `chrome.alarms`: ```typescript // WRONG — unreliable setTimeout(() =>