如何在Chrome扩展程序的内容脚本中导入ES6模块

拉格纳尔:

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] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章