Home >Web Front-end >JS Tutorial >How to Keep a Chrome Extension's Service Worker Persistent?

How to Keep a Chrome Extension's Service Worker Persistent?

Linda Hamilton
Linda HamiltonOriginal
2024-12-10 11:21:12678browse

How to Keep a Chrome Extension's Service Worker Persistent?

How to Persist a Service Worker in a Chrome Extension

Introduction

In standard Chrome extensions, service workers cannot be made persistent, which poses challenges for scenarios where intercepting data or maintaining state over long periods is crucial. This article explores various methods to overcome this limitation.

Workarounds

Bug Exploit (Chrome 110 )

Chrome 110 features a bug that allows service workers to remain active for 30 seconds longer by invoking any asynchronous Chrome API.

// background.js
const keepAlive = (i => state => {
  if (state && !i) {
    if (performance.now() > 20e3) chrome.runtime.getPlatformInfo();
    i = setInterval(chrome.runtime.getPlatformInfo, 20e3);
  } else if (!state && i) {
    clearInterval(i);
    i = 0;
  }
})();

async function doSomething() {
  try {
    keepAlive(true);
    const res = await (await fetch('........')).text();
    // ...........
  } catch (err) {
    // ..........
  } finally {
    keepAlive(false);
  }
}

Offscreen API (Chrome 109 )

This API allows creating offscreen documents that send messages every 30 seconds to keep the service worker active.

  • Manifest.json: "permissions": ["offscreen"]
  • offscreen.html:
  • offscreen.js: setInterval(() => (await navigator.serviceWorker.ready).active.postMessage('keepAlive'), 20e3);
  • background.js:

    async function createOffscreen() {
    await chrome.offscreen.createDocument({ url: 'offscreen.html', reasons: ['BLOBS'], justification: 'keep service worker running' }).catch(() => {});
    }
    chrome.runtime.onStartup.addListener(createOffscreen);
    createOffscreen();

NativeMessaging API (Chrome 105 )

Connecting to a nativeMessaging host via chrome.runtime.connectNative keeps the service worker running as long as the connection is active.

// background.js
const connect = () => {
  chrome.runtime.connectNative('nativemessaging_host').onDisconnect.addListener(connect);
};

connect(); // Start the connection on startup

WebSocket API (Chrome 116 )

Exchanging WebSocket messages less than every 30 seconds keeps the service worker active.

Dedicated Tab

Open a dedicated tab with an extension page that serves as a persistent background page.

The above is the detailed content of How to Keep a Chrome Extension's Service Worker Persistent?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn