'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).
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
