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

问题描述

在我的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内容不可用。

在此之前,我确实将background.js直接加载到manifest.json中,并将以下行添加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);
    

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...