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

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

问题描述

我正在尝试将chrome扩展名从清单版本2迁移到3.现在,后台脚本已由清单v3中的服务工作者替换,我不再可以使用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.

推荐答案

当前,您可以使用内置的此处跟踪).

请注意,由于Chrome中的错误,如果工作程序脚本在启动过程中引发错误,则工作程序根本不会注册,并且任何地方都不会显示错误.修复该错误之前的临时解决方法是将所有内容包装在try/catch中:

Note that due to a bug in Chrome, if the worker script throws an error during start, the worker won't be registered at all and there'll be no error displayed anywhere. The temporary workaround until the bug is fixed is to wrap everything in try/catch:

manifest.json 指定bg-loader.js,其中必须位于根路径中:

manifest.json specifies bg-loader.js that must be in the root path:

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

bg-loader.js ,整个文件只是其他脚本的包装:

bg-loader.js, the entire file is just a wrapper for other scripts:

try {
  importScripts('/path/file.js', '/path2/file2.js', '/path3/file3.js' /*, and so on */);
} catch (e) {
  console.error(e);
}

警告!!如果在导入文件的编译(语法错误,如未封闭的括号)或初始化(访问未定义的变量)的过程中,在导入的文件中发生未处理的异常,则导入将在该文件处停止,并且不进行任何操作.随后的文件将被导入.如果要忽略此类错误并继续导入,请在其自己的try-catch块中分别导入此文件.

Warning! If an unhandled exception occurs in an imported file during its compilation (syntax error like an unclosed parenthesis) or initialization (accessing an undefined variable), the import will stop at that file and 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.

警告!不要导入像 jQuery 这样的基于DOM的库,因为服务工作者没有DOM,因此没有 document XMLHttpRequest ,依此类推.

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.

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

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