gpt4 book ai didi

javascript - 如何在 Firefox WebExtension 的后台脚本中导入/使用外部 JavaScript 文件?

转载 作者:行者123 更新时间:2023-12-04 15:19:37 25 4
gpt4 key购买 nike

在我的 WebExtension 的后台脚本中,我想使用来自另一个 JavaScript 文件的函数/常量。但是,尽管听起来很简单,但我无法让它发挥作用。

我使用以下四个文件作为我的问题的最小示例:

  1. manifest.json:

    {
    "manifest_version": 2,
    "name": "MinimalCompleteReproducibleExample",
    "version": "0.0.0.0",

    "background": {
    "page": "background.html"
    }
    }

    它基本上只是加载 background.html 作为后台脚本/页面。

  2. 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

  3. mylib.js:

    export const foo = 42;

    它只是导出常量 foo

  4. background.js:

    console.log(foo);

    它尝试使用“外部”JavaScript 文件 mylib.js 的内容。

当我加载此扩展时,我在调试器中收到以下错误消息:

Uncaught ReferenceError: foo is not defined

这似乎表明 mylib.js 的内容不可用。

在此之前,我确实在 manifest.json 中直接加载了 background.js 并在 background.js 中添加了以下行:

import { foo } from "/mylib.js";

但这在 WebExtensions 中似乎是不允许的,也不起作用:

Uncaught SyntaxError: import declarations may only appear at top level of a module

那么有人能告诉我,如何在后台脚本中提供另一个 JavaScript 文件吗?

最佳答案

wOxxOm's comment帮我解决了。需要进行两处更改:

  • 添加 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然后可以省略。

完整的工作示例:

  1. manifest.json :
    {
    "manifest_version": 2,
    "name": "MinimalCompleteReproducibleExample",
    "version": "0.0.0.0",

    "background": {
    "page": "background.html"
    }
    }
  2. background.html :
    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="UTF-8">
    </head>
    <body>
    <script type="module" src="/background.js"></script>
    </body>
    </html>
  3. mylib.js :
    export const foo = 42;
  4. background.js :
    import { foo } from "/mylib.js";
    console.log(foo);

关于javascript - 如何在 Firefox WebExtension 的后台脚本中导入/使用外部 JavaScript 文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63619663/

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