Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

164
Views
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"]
);
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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"]
  );
})();

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!