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.html
as 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.js
that contains the functions/constants I want to reuse and the actual background script background.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?
wOxxOm's comment helped me solving it. Two changes are necessary:
type="module"
to <script src="background.js"></script>
in background.html
import { foo } from "/mylib.js";
to background.js
The line <script type="module" src="/mylib.js"></script>
in background.html
can then be omitted.
Complete working example:
manifest.json
:
{
"manifest_version": 2,
"name": "MinimalCompleteReproducibleExample",
"version": "0.0.0.0",
"background": {
"page": "background.html"
}
}
background.html
:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
</head>
<body>
<script type="module" src="/background.js"></script>
</body>
</html>
mylib.js
:
export const foo = 42;
background.js
:
import { foo } from "/mylib.js";
console.log(foo);