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

200
Views
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
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!