chrome 扩展 mv3 - 模块化服务工作者 js 文件 [英] chrome extension mv3 - Modularize service worker js file

本文介绍了chrome 扩展 mv3 - 模块化服务工作者 js 文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将我的 chrome 扩展从 manifest 版本 2 迁移到 3.现在后台脚本被 manifest v3 中的 service workers 替换,我不能再使用 html 文件并引用 js 文件在脚本标签中.

I am trying to migrate my chrome extension from manifest version 2 to 3. Now that background scripts are replaced by service workers in manifest v3, I can no longer use a html file and refer js files in script tags.

有什么方法可以将我的单个脚本文件导入到 service_worker.js 文件中?

Is there any way I can import my individual script files into the service_worker.js file?

我在互联网上搜索了几乎所有内容,但找不到任何解决方案.即使这里的官方文档注册后台脚本也没有那么有用.任何帮助将不胜感激.

I search almost everything on internet and couldn't find any solution. Even the official docs here Register background scripts were not so helpful. Any help would be appreciated.

推荐答案

首先,重要警告:

  • 警告!由于架构限制,如果在编译(如未闭括号的语法错误)或初始化(例如访问一个未定义的变量)所以我们将把代码包装在 try/catch 中.请注意,在 Chrome 93 之前,错误未在任何地方显示(它是一个 bug),现在它显示在chrome://extensions 页面中扩展卡上的错误列表.

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

警告!worker 文件必须位于根路径中在 93 之前的 Chrome 版本中.

Warning! The worker file must be in the root path in Chrome versions older than 93.

警告!不要导入像 jQuery 这样的基于 DOM 的库,因为 Service Worker 没有 DOM,所以没有 documentXMLHttpRequest 等.

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.

manifest.json:

manifest.json:

"background": { "service_worker": "bg-loader.js" },

bg-loader.js 只是单独文件中实际代码的 try/catch 包装器:

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);
}

如果某个文件抛出错误,则不会导入后续文件.如果您想忽略此类错误并继续导入,请在其自己的 try-catch 块中单独导入此文件.

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.

不要忘记指定文件扩展名,通常是 .js.mjs.

Don't forget to specify a file extension, typically .js or .mjs.

根据规范,我们必须使用 Service Worker 的 install 事件并导入我们希望能够稍后在异步事件中导入的所有脚本(从技术上讲,初始 install 之外的任何脚本JS 事件循环的 em>任务).仅在安装或更新扩展程序或重新加载解压缩的扩展程序时调用此处理程序(因为它等于更新).

Per the specification, we must use a service worker's install event and import all the scripts that we want to be able to import in an asynchronous event later (technically speaking, anything outside of the initial task of the JS event loop). This handler is called only when the extension is installed or updated or an unpacked extension is reloaded (because it's equal to an update).

这在 MV3 中很复杂,因为 Service Worker 是为 Web 设计的,在这种情况下,远程脚本可能无法离线使用.希望它会在 crbug/1198822 中得到简化.

It's this convoluted in MV3 because service workers were designed for the Web, where remote scripts may be unavailable offline. Hopefully, it'll be simplified in crbug/1198822.

另见:webpack-target-webextension 用于 WebPack 的插件.

See also: webpack-target-webextension plugin for WebPack.

self.oninstall = () => {
  tryImport('/js/some-complex-script.js');
};

function tryImport(...fileNames) {
  try {
    importScripts(...fileNames);
    return true;
  } catch (e) {
    console.error(e);
  }
}

chrome.runtime.onMessage.addListener((msg, sender, sendResponse) => {
  if (msg.action === 'somethingComplex') {
    if (tryImport('/js/some-complex-script.js')) {
      // calling a global function from some-complex-script.js
      someComplexScriptAsyncHandler(msg, sender, sendResponse);
      return true;
    }
  }
});

2.Chrome 92 及更新版本中的 ES 模块

通过在 manifest.json 中的 background 声明中添加 "type": "module" 来启用.

2. ES modules in Chrome 92 and newer

Enabled by adding "type": "module" to the declaration of background in manifest.json.

  • 可以使用静态import 语句.
  • 动态 import() 尚未实现(crbug/1198822).
  • Static import statement can be used.
  • Dynamic import() is not yet implemented (crbug/1198822).

manifest.json:

manifest.json:

"background": { "service_worker": "bg.js", "type": "module" },
"minimum_chrome_version": 92,

bg.js:

模块名称必须以路径开头,以 .js 或 .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() {
  // .........
}

这篇关于chrome 扩展 mv3 - 模块化服务工作者 js 文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆