Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I remove an injected CSS file?

I use chrome.tabs.insertCSS(null, {file: "style.css"}); to insert a css file into the page, and it works fine.

  • But is there a way to remove the file?
  • Also, if I inject another file named style.css, does it override the first one?
  • And by the way, where can I see the injected CSS files? Scripts can be viewed in "Sources/Content Scripts" (of chrome developer tools), but I cannot find the CSS files.
like image 378
JMaylin Avatar asked Aug 30 '13 13:08

JMaylin


2 Answers

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:

  • wrap your custom styles in something like body.JMaylinCustomStyles
  • use JavaScript to add or remove the JMaylinCustomStyles class to the body element.
  • there is no step 3.

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.

like image 106
Timothée Boucher Avatar answered Sep 21 '22 12:09

Timothée Boucher


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.

like image 45
David Gilbertson Avatar answered Sep 20 '22 12:09

David Gilbertson