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.
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.
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!