ganoro
ganoro

Reputation: 518

After injecting CSS or JavaScript with chrome.tabs.*, how to remove it?

I used "chrome.tabs.insertCSS" to inject CSS into a page. I would like to add an option to the user to remove this css (with a button or something).

The question is then - how do I remove this css/js (programmatically) addition from the tab?

Upvotes: 2

Views: 926

Answers (1)

serg
serg

Reputation: 111265

Instead of injecting styles automatically, manually create <style> element with some id, which you can later remove from the DOM.

Here is a snapshot from an extension that enables and disables link underlining through css:

//enable.js
var head = document.head;
var style = document.createElement("style");
var rules = document.createTextNode("a {text-decoration:underline !important;}");

style.type = "text/css";
style.id = "__link-highlighter";
if(style.styleSheet) {
    style.styleSheet.cssText = rules.nodeValue;
} else { 
    style.appendChild(rules);
}
head.appendChild(style);


//disable.js
if(document.getElementById("__link-highlighter")) {
    document.head.removeChild(document.getElementById("__link-highlighter"));
}

I am injecting CSS rules into the body of <style> element because they are very small, if you need a lot of rules you should be able to create <link rel="stylesheet"> instead linking to chrome.extension.getURL("styles.css").

Upvotes: 3

Related Questions