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

這個問題的解法:

Migrate to a service worker
https://developer.chrome.com/docs/extensions/develop/migrate/to-service-workers

沒想到這麼快就來到 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 chrome.storage.local.set({ '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() {
  clearInterval(heartbeatInterval);
}

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

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

chrome://serviceworker-internals


Extension service worker basics
https://developer.chrome.com/docs/extensions/develop/concepts/service-workers/basics#import-scripts

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.

importScripts('locales.js');

範例:

Sample CO₂ Meter Chrome Extension
https://github.com/GoogleChrome/chrome-extensions-samples/tree/main/functional-samples/sample.co2meter

發佈留言

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