Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
306 views
in Technique[技术] by (71.8m points)

javascript - Inserting CSS with a Firefox Extension

I'm building a Firefox extension that adds HTML elements to certain pages of a website. I want to have it insert a custom CSS file to style those elements. It works if I insert tags with the CSS right on the page, but that's a less than ideal solution.

Is there anyway to get it to load and parse a CSS file, as if I used the tag in the header, or am I stuck inlining it somehow?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

chrome:// won't work because the page you are inserting into isn't allowed to access files outside of it's domain (including chrome URIs). This is true even you are the one inserting the link, because the link is still executed in the context of the target page. Instead you have two options:

You can define a resource protocol alias in your manifest and then use a resource URI to access the CSS. For example, the following chrome.manifest will allow you to insert the css as resource://myextresource/myfile.css:
content myext content/
resource myextresource content/css/
See MDN Chrome registration for more info. Also see How can a Firefox extension inject a local css file into a webpage? for a similar question.

Or, you can add the CSS as a USER_SHEET using the following. This will make your CSS available across all pages, so be sure you use very unique selectors. One caveat with this approach is that the page CSS has precedence over user sheets. You can use !important to override that, but the page CSS can still trump you if it uses !important as well.

var sss = Components.classes["@mozilla.org/content/style-sheet-service;1"]
    .getService(Components.interfaces.nsIStyleSheetService);
var ios = Components.classes["@mozilla.org/network/io-service;1"]
    .getService(Components.interfaces.nsIIOService);
var uri = ios.newURI(url, null, null);
sss.loadAndRegisterSheet(uri, sss.USER_SHEET);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...