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
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);