Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

202
Visualizações
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 à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda