Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

166
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda