Inject a CSS file into a webpage via firefox exten

2020-02-28 06:25发布

问题:

I am writing a Firefox extension and I am using their Add-on SDK; but I can't figure out how to inject a local CSS file from the data folder into the webpage. It would be great if there were a way to do it via page_mod package.

回答1:

As of Add-on SDK 1.14 there's experimental (API may change) support for this in the page-mod module:

var pageMod = require("sdk/page-mod").PageMod({
  include: "*",
  contentStyleFile: require("sdk/self").data.url("my-style.css")
});

See Modifying Web Pages Based on URL for an elaborate guide to using page-mod.

There's a page on the Addon SDK's wiki discussing issues with the current implementation, although it seems a bit outdated.

Under the hood it uses nsIDOMWindowUtils.loadSheet() to add the stylesheet without touching the page's DOM. (This API was added in Firefox 18, see bug 737003. Before that you had to use nsIStyleSheetService which was similar, but not tab-specific.)


Before that you could use the page-mod's content script to insert the link or style element (example). [edit] thanks to lwburk's comment, here's a more elaborate elaborate description in Greasemonkey Hacks: Tips & Tools for Remixing the Web with Firefox By Mark Pilgrim: "Alter a Page's Style" section.



回答2:

To insert CSS from main.js one can now use "page-mod":

var data = require("sdk/self").data;
var pageMod = require("sdk/page-mod");

pageMod.PageMod({
  include: "*.org",
  contentStyleFile: data.url("my-page-mod.css")
});