gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 17:20:08 37 4
gpt4 key购买 nike

Chrome 61 , 添加了对 JavaScript 模块的支持。现在我正在运行 Chrome 63。

我正在尝试使用 import/export Chrome 扩展内容脚本中的语法以使用模块。

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"> 语法),还是我做错了什么?谷歌会忽略对扩展的支持似乎很奇怪。

最佳答案

如前所述,对于后台脚本,最好使用 background.page并使用 <script type="module">踢你的 JavaScript。

问题是content script , 并注入(inject) <script>带有 type 的标签属性可以是一个解决方案。

注入(inject)脚本标签之外的另一种方法是使用 dynamic import功能。通过这种方法,您不需要放开 chrome 的范围。模块并且仍然可以使用 chrome.runtime或其他模块。

  • Dynamic import()

  • content_script.js , 看起来像

    (async () => {
    const src = chrome.runtime.getURL("your/content_main.js");
    const contentMain = await import(src);
    contentMain.main();
    })();

    您还需要在 list 的 Web Accessible Resources 中声明导入的脚本。 :
    {
    "web_accessible_resources": [
    "your/content_main.js"
    ]
    }

    更多细节:
  • How to use ES6 “import” with Chrome Extension
  • Working Example of ES6 import in Chrome Extension
  • chrome.runtime.getURL

  • 希望能帮助到你。

    关于javascript - 如何在 Chrome 扩展的内容脚本中导入 ES6 模块,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58480046/

    37 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com