10

In Google Chrome extensions before manifest v3 I could divide background.js into multiple scripts. And to load all scripts to be visible in background.js I only need to to put them in array in manifest like this:

    "background": {
    "scripts": ["helpers/countHelper.js", "helpers/networkHelper.js", "background/main.js"],
}

With this above sintax, all scripts will be merged into one file.

Now in documentation how to use manifest v3, they wrote:

Replace background.page or background.scripts with background.service_worker in manifest.json. Note that the service_worker field takes a string, not an array of string.

Cause background in manifest can't take multiple scripts, how to divide background script into multiple scripts. Also import syntax is not allowed as I know.

Predrag Davidovic
  • 1,411
  • 1
  • 17
  • 20

1 Answers1

12

With this above sintax, all scripts will be merged into one file.

It is not true, but let's fly over...

You can use importScript but not in manifest. Look at this template:

/* V3 manifest.json */
"background": {
    "service_worker": "worker_wrapper.js"
},

/* worker_wrapper.js */
try {
    importScripts("helpers/countHelper.js", "helpers/networkHelper.js", "background/main.js");
} catch (e) {
    console.log(e);
}

Bear in mind that SW file must be placed in root folder, whereas other scripts could be placed in other folders

Robbi
  • 1,254
  • 2
  • 8
  • 11
  • 4
    I am getting the error TypeError: Failed to execute 'importScripts' on 'WorkerGlobalScope': Module scripts don't support importScripts(). at background.ts:3:5 – rbansal Jul 24 '22 at 14:31
  • @rbansal Make sure to remove in the manifest file "type: module" from the background service_worker. Then it works. – mdiener Oct 07 '22 at 14:57
  • "Bear in mind that SW file must be placed in root folder" . why is that? Is it like a requirement of MV3 ? – Kritidipto Ghosh Feb 27 '23 at 12:42
  • You're right. It's no longer so – Robbi Feb 27 '23 at 19:25