I have a Chrome extension which adds a CSS to a website, and I want to have that CSS be able to be removed when the extension icon is clicked.
I was able to get the CSS to inject successfully but I was not able to properly find a way to remove the CSS. When I click the extension icon, it doesn’t remove the CSS. Instead, you need to click it serveral times for the CSS to be removed.
Here is the code I’m using as background.js
. It inserts CSS into the tab and then should remove the CSS when the action/extension is clicked:
chrome.tabs.onUpdated.addListener(async (tabId, changeInfo, tab) => {
if (tab.url?.startsWith('https://example.com')) {
await chrome.scripting.insertCSS({
files: ['style.css'],
target: { tabId: tabId }
});
await chrome.action.enable(tabId);
}
});
chrome.action.onClicked.addListener(async (tab) => {
if (tab.url?.startsWith('https://example.com')) {
await chrome.scripting.removeCSS({
files: ['style.css'],
target: { tabId: tab.id }
});
}
});
manifest.json
:
{
"manifest_version": 3,
"name": "__MSG_application_title__",
"description": "__MSG_application_description__",
"version": "1.0.0",
"default_locale": "en_US",
"icons": {
"16": "images/icon-16.png",
"32": "images/icon-32.png",
"48": "images/icon-48.png",
"128": "images/icon-128.png"
},
"background": {
"service_worker": "background.js"
},
"action": {
"default_title": "Toggle dark mode"
},
"host_permissions": [
"*://example.com/*"
],
"permissions": [
"scripting"
]
}
I tried calling chrome.scripting.removeCSS
multiple times which does solve the problem but for obvious code quality problems this solution isn’t satisfactory:
chrome.action.onClicked.addListener(async (tab) => {
if (tab.url?.startsWith('https://example.com')) {
await chrome.scripting.removeCSS({
files: ['style.css'],
target: { tabId: tab.id }
});
await chrome.scripting.removeCSS({
files: ['style.css'],
target: { tabId: tab.id }
});
await chrome.scripting.removeCSS({
files: ['style.css'],
target: { tabId: tab.id }
});
await chrome.scripting.removeCSS({
files: ['style.css'],
target: { tabId: tab.id }
});
await chrome.scripting.removeCSS({
files: ['style.css'],
target: { tabId: tab.id }
});
await chrome.scripting.removeCSS({
files: ['style.css'],
target: { tabId: tab.id }
});
await chrome.scripting.removeCSS({
files: ['style.css'],
target: { tabId: tab.id }
});
}
});
Does anyone know why this behavior happens and how to properly solve it?