javascriptfirefox-addon-webextensions

How to import/use an external JavaScript file in the background script of a Firefox WebExtension?


Inside the background script of my WebExtension I want to use functions/constants from another JavaScript file. But as simple as it sounds, I cannot get it to work.

I'm using the following four files as a minimal example for my problem:

  1. manifest.json:

    {
        "manifest_version": 2,
        "name": "MinimalCompleteReproducibleExample",
        "version": "0.0.0.0",
    
        "background": {
            "page": "background.html"
        }
    }
    

    It basically just loads background.html as the background script/page.

  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>
    

    It loads the "external" JavaScript file mylib.js that contains the functions/constants I want to reuse and the actual background script background.js.

  3. mylib.js:

    export const foo = 42;
    

    It just exports the constant foo.

  4. background.js:

    console.log(foo);
    

    It tries to use the content of the "external" JavaScript file mylib.js.

When I load this extension, I get the following error message in the debugger:

Uncaught ReferenceError: foo is not defined

That seems to indicate that the content of mylib.js is not available.

Before that, I did load the background.js directly in manifest.json and added the following line to background.js:

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

But that does not seem to be allowed in WebExtensions and also does not work:

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

So can someone tell me, how to make another JavaScript file available inside a background script?


Solution

  • wOxxOm's comment helped me solving it. Two changes are necessary:

    The line <script type="module" src="/mylib.js"></script> in background.html can then be omitted.

    Complete working example:

    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);