在我的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文件吗?
wOxxOm的评论帮助我解决了这个问题。必须进行两项更改:
type="module"
到<script src="background.js"></script>
在background.html
import { foo } from "/mylib.js";
到background.js
线<script type="module" src="/mylib.js"></script>
中background.html
,然后可被省略。
完整的工作示例:
manifest.json
: {
"manifest_version": 2,
"name": "MinimalCompleteReproducibleExample",
"version": "0.0.0.0",
"background": {
"page": "background.html"
}
}
background.html
: <!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
</head>
<body>
<script type="module" src="/background.js"></script>
</body>
</html>
mylib.js
: export const foo = 42;
background.js
: import { foo } from "/mylib.js";
console.log(foo);
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句