Travis Pettry
Travis Pettry

Reputation: 1352

Browser Extension Background Module

I am working on a browser extension that runs a background script. So far I have all of that working. My issue is I need to use a module in my background script. When I write the import statement I get the follwing exception:

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

How does one turn a background script into a module?

Manifest.json

{
  "name": "Extension Demo",
  "version": "1.0",
  "description": "Build an Basic Extension!",
  "permissions": [
    "activeTab",
    "webRequest",
    "webRequestBlocking",
    "<all_urls>"
  ],
  "browser_action": {
    "default_popup": "index.html",
    "default_icon": {
      "16": "img/icon16.png",
      "32": "img/icon32.png",
      "48": "img/icon48.png"
    }
  },
  "manifest_version": 2,
  "background": {
    "scripts": [ "background.js" ]
  }
}

bakground.js

import * as myMod from './myMod.js'


function redirect(requestDetails) {
    //do some awesome stuff
}

browser.webRequest.onBeforeRequest.addListener(
    redirect,
    { urls: ["<all_urls>"], types: ["page"] },
    ["blocking"]
);

Upvotes: 3

Views: 1472

Answers (1)

Leonardo Bagi
Leonardo Bagi

Reputation: 186

You are using manifest V2, and I highly recommend updating to Manifest v3 to latest features and your error fix.

In your manifest.json file, pass "type": "module" inside the object to allow ESM imports.

"background": {
    "service_worker": "background.js",
    "type": "module"
}

Alternatively, in case you still want to use V2, use a dynamic import instead. Keep in mind that those returns promises and you will have to await it or use a .then() statement.

(async () => {

  const myMod = await import("./myMod.js");
  // if myMod.js uses an `export default` statement, use `(await import("./myMod.js")).default` instead.

  function redirect(requestDetails) {
    //do some awesome stuff
  }

  browser.webRequest.onBeforeRequest.addListener(
    redirect,
    { urls: ["<all_urls>"], types: ["page"] },
    ["blocking"]
  );
})();

Upvotes: 6

Related Questions