开发者

Inserting CSS with a Firefox Extension

开发者 https://www.devze.com 2022-12-28 04:40 出处:网络
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 inserttags with the CSS right o

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开发者_JAVA百科 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?


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

精彩评论

暂无评论...
验证码 换一张
取 消