On user action (click on button in popup) my extension will use browser.tabs.executeScript
on given tab.
On consecutive user actions I just want the already injected script to react onMessage, but don’t want to insert the content script again.
What is the best way to check if a content script is already present?
Some possible solutions:
A)
Some developers would execute a script just for adding a variable with a boolean value to window
and then - before executing their content script - check that boolean (by using a distinct call to executeScript
).
B)
One could manually keep track (in a store file) of tab ids that a script has been inserted into, then use tabs.onUpdated.addListener
to remove a given record from the store).
C)
const hasContentScript = async tabId => {
try {
await browser.tabs.sendMessage(tabId, {/*...*/});
return true;
} catch (error) {
// maybe check error first here (could be sth else than missing recipient)
return false;
}
};
A seems too much overhead, B is very error-prawn (i.e. when reloading a page FF will fire with an url change, whereas chrome doesn’t).
I came up with C, but would like some feedback if this is a good idea or not - Thank you!