在Chrome 61中,添加了对JavaScript模块的支持。现在,我正在运行Chrome 63。
我正在尝试在Chrome扩展程序内容脚本中使用import
/ export
语法来使用模块。
在manifest.json
:
"content_scripts": [
{
"js": [
"content.js"
],
}
]
在my-script.js
(与相同的目录中content.js
):
'use strict';
const injectFunction = () => window.alert('hello world');
export default injectFunction;
在content.js
:
'use strict';
import injectFunction from './my-script.js';
injectFunction();
我收到此错误: Uncaught SyntaxError: Unexpected identifier
如果将导入语法更改为import {injectFunction} from './my-script.js';
以下错误:Uncaught SyntaxError: Unexpected token {
content.js
在Chrome扩展程序中使用此语法是否存在一些问题(因为在HTML中您必须使用<script type="module" src="script.js">
语法),或者我做错了什么?Google忽略对扩展的支持似乎很奇怪。
我设法找到一种解决方法。
首先,必须要说的是,自2018年1月起,内容脚本不支持模块。此解决方法通过将模块script
标签嵌入到导致扩展的页面中,从而避开了限制。
这是我的manifest.json
:
"content_scripts": [ {
"js": [
"content.js"
]
}],
"web_accessible_resources": [
"main.js",
"my-script.js"
]
请注意,我在中有两个脚本web_accessible_resources
。
这是我的content.js
:
'use strict';
const script = document.createElement('script');
script.setAttribute("type", "module");
script.setAttribute("src", chrome.extension.getURL('main.js'));
const head = document.head || document.getElementsByTagName("head")[0] || document.documentElement;
head.insertBefore(script, head.lastChild);
这将main.js
作为模块脚本插入到网页中。
我所有的业务逻辑现在都在main.js
。
为了使此方法起作用,main.js
(以及我将要使用的所有脚本import
)必须web_accessible_resources
在清单中。
my-script.js
'use strict';
const injectFunction = () => window.alert('hello world');
export {injectFunction};
而在main.js
这导入脚本的例子:
'use strict';
import {injectFunction} from './my-script.js';
injectFunction();
这可行!没有错误,我很高兴。:)
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句