Search code examples
javascriptgoogle-chromegoogle-chrome-extensioncode-injection

How do I make it so my Chrome extension will only inject a script once?


I'm using programmatic injection to inject my extension's code into a page only when the browser action is clicked.

This is what I have on my extension's event page (per the example in the documentation):

chrome.browserAction.onClicked.addListener(function callback(tab){
  chrome.tabs.executeScript(null, {file: "content-script.js"});
});

However, the way this works, the script is injected every time the button is clicked.

How can I change it so that the script is not injected on subsequent button presses - so that it is inserted only the first time the button is clicked on that page?


Solution

  • Put a global variable in your contentscript to judge if the contentscript has been executed.

    if (something) { return; }