How to import a js file in a Chrome extension service worker?

Posted in :


Migrate to a service worker

沒想到這麼快就來到 JS 的 module 的世界。

透過下列程式碼, 讓 service worker 持續上班:

Use the following code snippet to keep your service worker alive:

 * Tracks when a service worker was last alive and extends the service worker
 * lifetime by writing the current time to extension storage every 20 seconds.
 * You should still prepare for unexpected termination - for example, if the
 * extension process crashes or your extension is manually stopped at
 * chrome://serviceworker-internals.
let heartbeatInterval;

async function runHeartbeat() {
  await{ 'last-heartbeat': new Date().getTime() });

 * Starts the heartbeat interval which keeps the service worker alive. Call
 * this sparingly when you are doing work which requires persistence, and call
 * stopHeartbeat once that work is complete.
async function startHeartbeat() {
  // Run the heartbeat once at service worker startup.
  runHeartbeat().then(() => {
    // Then again every 20 seconds.
    heartbeatInterval = setInterval(runHeartbeat, 20 * 1000);

async function stopHeartbeat() {

 * Returns the last heartbeat stored in extension storage, or undefined if
 * the heartbeat has never run before.
async function getLastHeartbeat() {
  return (await'last-heartbeat'))['last-heartbeat'];

service worker 的 console.log 要透過這裡去看:


Extension service worker basics

To use the import statement, add the "type" field to your manifest and specify "module". For example:

  "background": {
    "service_worker": "service-worker.js",
    "type": "module"

Then use import as you normally would. Note that import assertions are not supported.

import { tldLocales } from './locales.js';

Use importScripts() as you would in a web service worker.



Sample CO₂ Meter Chrome Extension


發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *