In 铬61,添加了对 JavaScript 中模块的支持。现在我运行的是 Chrome 63。
我正在尝试使用import
/export
Chrome 扩展内容脚本中的语法以使用模块。
In manifest.json
:
"content_scripts": [
{
"js": [
"content.js"
],
}
]
In my-script.js
(与相同的目录content.js
):
'use strict';
const injectFunction = () => window.alert('hello world');
export default injectFunction;
In 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">
语法),或者我做错了什么?谷歌会忽略对扩展的支持,这似乎很奇怪。
Use the dynamic import() https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/import功能。
与使用不安全的解决方法不同<script>
element,这个运行在相同的安全 JS 环境(内容脚本的隔离世界)中,您导入的模块仍然可以访问初始内容脚本的全局变量和函数,包括内置的chrome
类似APIchrome.runtime.sendMessage
.
In content_script.js
, 看起来像
(async () => {
const src = chrome.runtime.getURL("your/content_main.js");
const contentMain = await import(src);
contentMain.main();
})();
您还需要在清单中声明导入的脚本网络可访问资源 https://developer.chrome.com/extensions/manifest/web_accessible_resources:
// 清单V3
"web_accessible_resources": [{
"matches": ["<all_urls>"],
"resources": ["your/content_main.js"]
}],
// 清单V2
"web_accessible_resources": [
"your/content_main.js"
]
更多细节:
- 如何通过 Chrome 扩展使用 ES6“导入” https://medium.com/@otiai10/how-to-use-es6-import-with-chrome-extension-bd5217b9c978
- Chrome 扩展中 ES6 导入的工作示例 https://github.com/otiai10/chrome-extension-es6-import
- chrome.runtime.getURL https://developer.chrome.com/extensions/runtime#method-getURL
希望能帮助到你。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)