chrome-ext-service-workerlisted
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(() =>