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:
manifest.json:{ "manifest_version": 2, "name": "MinimalCompleteReproducibleExample", "version": "0.0.0.0", "background": { "page": "background.html" } }It basically just loads
background.htmlas the background script/page.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.jsthat contains the functions/constants I want to reuse and the actual background scriptbackground.js.mylib.js:export const foo = 42;It just exports the constant
foo.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?
type="module"to your background script declaration as well.