'Manifest V3 - import class in the service_worker
im trying to import a class in my service worker, in my Chrome Extension
So this is what I have at the beginning of the file :
/*global chrome*/
try {
importScripts("utils/utils.js");
} catch (e) {
console.log(e);
}
and this is the function where I call the class :
async function injectPopup() {
try {
let b = new Utils();
} catch (e) {
console.log(e);
}
.
.
.
the console.log is printing me this :
ReferenceError: Utils is not defined
at injectPopup (<anonymous>:4:17)
at <anonymous>:28:3
this is the content of utils/utils.js :
class utils {
test() {
console.log("foooo");
}
}
Can you tell me how am I supposed to call the classes ? the goal is to have a cleaner code with and not all the logic in the same service_worker, so if there is another better practice I would love to know
Thanks !
Solution 1:[1]
In my case there were two problems :
First, as wOxxOm commented, I needed to create a global variable in the service_worker file :
/*global chrome*/
let globals = {}; // HERE
try {
importScripts("utils/Utils.js");
} catch (e) {
console.log(e);
}
And in the class declaration to add it to the global like this :
globals.Utils = class Utils {
test() {
console.log("foo");
}
}
The second problem was that I was calling it from a function given to chrome.scripting.executeScript which cannot work, because the script is executed by itself in the given tab Javascript and not in the popup Javascript, and this is why the class could not be found.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | cbdev |
