WittCode💻

Persisting Service Workers

By

Learn how to keep service workers alive for longer than 30 seconds using the Runtime API and long-lived connections.

Table of Contents 📖

Service Worker Lifecycle

Service workers follow a lifecycle of installation, startup, and shutdown. The shutdown stage of the lifecycle is where the service worker goes idle. Specifically, the service worker goes idle if it has not received any events for 30 seconds.

Prolonging the Service Worker

The key here is that the service worker will not shut down if it consistently receives events. The 30 second timer is reset every time it receives an event. Consistently sending events to a service worker can be done in several ways, one of which is using long-lived connections of the Runtime API.

The Code

{
  "manifest_version": 3,
  "name": "Sample Extension",
  "version": "1.0.0",
  "description": "Sample extension",
  "content_scripts": [
    {
      "matches": ["<all_urls>"],
      "js": ["content.js"]
    }
  ],
  "background": {
    "service_worker": "service.js",
    "type": "module"
  }
}
const port = chrome.runtime.connect();

port.onMessage.addListener((message) => {
  console.log(message); // pong
});

// Keep the service worker alive
setInterval(() => {
  port.postMessage('ping');
}, 10000);
// Connect to content scripts
chrome.runtime.onConnect.addListener((port) => {
  port.onMessage.addListener((message) => {
    console.log(message); // ping
    port.postMessage('pong');
  });
});

Here we send a message to the service worker every 10 seconds. This will keep the service worker alive as long as the tab the content script is injected into is alive.