问题描述
在我的WebExtension的后台脚本中,我想使用另一个JavaScript文件中的函数/常量。但是听起来很简单,但我无法使其正常工作。
我使用以下四个文件作为解决问题的最小示例:
-
manifest.json
:{ "manifest_version": 2,"name": "MinimalCompleteReproducibleExample","version": "0.0.0.0","background": { "page": "background.html" } }
基本上,它仅加载
background.html
作为后台脚本/页面。 -
background.html
:<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> </head> <body> <script type="module" src="/mylib.js"></script> <script src="background.js"></script> </body> </html>
它会加载“外部” JavaScript文件
mylib.js
,其中包含我要重用的函数/常量以及实际的后台脚本background.js
。 -
mylib.js
:export const foo = 42;
它仅导出常量
foo
。 -
background.js
:console.log(foo);
它尝试使用“外部” JavaScript文件
mylib.js
的内容。
加载此扩展名时,在调试器中收到以下错误消息:
Uncaught ReferenceError: foo is not defined
这似乎表明mylib.js
的内容不可用。
在此之前,我确实将background.js
直接加载到manifest.json
中,并将以下行添加到background.js
中:
import { foo } from "/mylib.js";
但这似乎在WebExtensions中是不允许的,并且也不起作用:
Uncaught SyntaxError: import declarations may only appear at top level of a module
那么有人可以告诉我,如何在后台脚本中提供另一个JavaScript文件吗?
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)