First off, important warnings:
Warning! Due to an architectural limitation the service worker can't be registered if an unhandled exception occurs during its compilation (a syntax error like an unclosed parenthesis) or initialization (e.g. accessing an undefined variable) so we'll wrap the code in try/catch
. Note that until Chrome 93 the error wasn't shown anywhere (it was a bug), now it's shown in the error list on the extension card in chrome://extensions page.
Warning! The worker file must be in the root path in Chrome versions older than 93.
Warning! Don't import DOM-based libraries like jQuery because service workers don't have DOM so there's no document
, XMLHttpRequest
, and so on.
This built-in function synchronously fetches and runs the scripts so their global variables and functions become available immediately. It can only be used in the first JS event loop task while the worker initializes i.e. you can't call it later from an event listener (crbug).
manifest.json:
"background": { "service_worker": "bg-loader.js" },
bg-loader.js is just a try/catch wrapper for the actual code in separate files:
try {
importScripts('/path/file.js', '/path2/file2.js' /*, and so on */);
} catch (e) {
console.error(e);
}
If some file throws an error, no subsequent files will be imported. If you want to ignore such errors and continue importing, import this file separately in its own try-catch block.
2. ES modules in Chrome 92 and newer
Enabled by adding "type": "module"
to the declaration of background
in manifest.json.
- Static
import
statement can be used.
- Dynamic
import()
is not yet implemented (crbug).
manifest.json:
"background": { "service_worker": "bg.js", "type": "module" },
"minimum_chrome_version": 92,
bg.js:
Module names must start with a path and end with an extension like .js or .mjs
import {foo} from '/path/file.js';
import './file2.js';
// each imported module should also use try/catch for their own init
try { init(); } catch (e) { console.error(e); }
function init() {
// .........
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…