I use chrome.tabs.insertCSS(null, {file: "style.css"});
to insert a css file into the page, and it works fine.
style.css
, does it override the first one?I'm not sure what the context of this question is, but it sounds like maybe you want to highlight specific elements of the page a certain way and be able to toggle that custom highlight. (rather than styling elements your extension would create)
Since you can't actually remove the CSS file or just erase it by adding a file with the same name, I suggest the following:
body.JMaylinCustomStyles
JMaylinCustomStyles
class to the body
element.The benefits are that it doesn't add much work on top of what you have, that you don't have to figure out how to override your custom styles in a second stylesheet (it's always very annoying and error-prone) and that you even gain a bit in CSS specificity so your styles are more likely to be applied.
Note that the best way to "wrap" your styles would be to use Sass or LESS since you can literally just add body.JMaylinCustomStyles {
at the top of the file and }
at the bottom.
I've just come up against the same problem and thought I'd share my solution. I'm calling a content script that will then load or unload the css like so:
function loadCSS(file) {
var link = document.createElement("link");
link.href = chrome.extension.getURL(file + '.css');
link.id = file;
link.type = "text/css";
link.rel = "stylesheet";
document.getElementsByTagName("head")[0].appendChild(link);
}
function unloadCSS(file) {
var cssNode = document.getElementById(file);
cssNode && cssNode.parentNode.removeChild(cssNode);
}
The logic for which of those to call is also in the content script, based on data in chrome.storage
. So all you need to do is inject the script and it will add/remove the css.
My case is actually a little more complex so I'm always loaded the content script and sending a message to it to load or unload the css. But this has the overhead of loading the file on every page load.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With