You can implement something like this in the background file,
Steps
- Create an Array of domains which has been specified in your content script.
- Add a listener on the tab selection changed and tab updated.
- Checkout the currently active tab is in your array or not.
- Set a flag value true false using the above check.
- On extension click now, check if the flag is true then perform the task else ignore the click.
let activeExtension = false;
const contentScriptMatchArray = ['https://www.google.com', 'https://www.youtube.com'];
chrome.tabs.onActivated.addListener(handleExtensionActiveState);
chrome.tabs.onUpdated.addListener((tabId, changeInfo, tab) => {
handleExtensionActiveState(tab);
});
function handleExtensionActiveState(tabs) {
if (tabs.tabId) {
chrome.tabs.get(tabs.tabId, (tab) => {
activeExtension = checkWhiteListedOrigin(tab);
});
} else {
activeExtension = checkWhiteListedOrigin(tabs);
}
}
function checkWhiteListedOrigin(tab) {
const tabURl = new URL(tab.url);
return contentScriptMatchArray.includes(tabURl.origin);
}
chrome.browserAction.onClicked.addListener(function () {
if (activeExtension) {
console.log('Clicked');
}
});
Note
- you can also change your extension icon, so your extension will look like it's actually disabled
References