Chrome Extension Service Worker Keepalive — Best Practices

2 min read

Service Worker Keep-Alive Patterns

Understanding MV3 Service Worker Lifecycle

Chrome’s Manifest V3 service workers have strict lifetime limits:

This differs significantly from MV2 background pages which could run indefinitely.

Legitimate Keep-Alive Patterns

1. Active Port Connections {#1-active-port-connections}

The most reliable way to keep a service worker alive is through active port connections:

// From popup/background script
const port = chrome.runtime.connect({ name: 'keepalive' });

// Service worker - handle the connection
chrome.runtime.onConnect.addListener((port) => {
  // Service worker stays alive while port is connected
  port.onDisconnect.addListener(() => {
    // Cleanup when popup closes
  });
});

2. Alarm-Based Periodic Tasks {#2-alarm-based-periodic-tasks}

For scheduled background work, use chrome.alarms API:

// Create alarm (minimum 30s in dev, 1min in production)
chrome.alarms.create('periodic-task', {
  delayInMinutes: 1,
  periodInMinutes: 1
});

chrome.alarms.onAlarm.addListener((alarm) => {
  if (alarm.name === 'periodic-task') {
    // Perform periodic work
  }
});

3. Offscreen Documents {#3-offscreen-documents}

For truly persistent work requiring long-running operations:

// Create offscreen document
await chrome.offscreen.createDocument({
  url: 'offscreen.html',
  reasons: ['WORKERS', 'LOCAL_STORAGE'],
  justification: 'Background data processing'
});

Anti-Patterns to Avoid

When to Use Keep-Alive vs Event-Driven Design

Use keep-alive when:

Redesign for event-driven when:

Chrome’s Reasoning

These limits exist for good reasons:

Testing and Debugging

Monitor service worker lifecycle at: chrome://serviceworker-internals

Graceful Shutdown Pattern

Always save state before termination:

let pendingData = [];

chrome.runtime.onSuspend.addListener(() => {
  // Persist any pending data
  chrome.storage.local.set({ suspendedData: pendingData });
});

Part of the Chrome Extension Guide by theluckystrike. Built at zovo.one.