Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 905
Stuart P. Bentley Avatar asked Feb 15 '23 11:02

Stuart P. Bentley


1 Answers

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

if (something) { return; }
like image 121
Tom Avatar answered Feb 18 '23 03:02

Tom