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

209
Vistas
Injecting content script programmatically to chrome extension multiple times throws syntax error

I am new to extension development. I am trying to inject a content script programmatically as described in the documentation.

This is my background.js.

chrome.action.onClicked.addListener((tab) => {
  try {
    chrome.scripting.executeScript({
      target: { tabId: tab.id },
      files: ["content-script.js"],
    });
  } catch (err) {
    console.log(err);
  }
});

And this is my conten-script.js.

const message = "Hello Stranger";
window.alert(message);

Clicking the extension icon more than once throws the error below.

Uncaught SyntaxError: Identifier 'message' has already been declared (at content-script.js:1:1)

But when I run the same code in a function, it works just fine.

(function () {
  const message = "Hello Stranger";
  window.alert(message);
})();

It looks like chrome has some kind of "global environment" where the script runs and that environment maintains references to the variables declared in the previous execution. I would love to know what is happening here. The documentation doesn't have an explanation( I am yet to come across if it does).

about 4 years ago · Santiago Trujillo
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