Inject a CSS file into a webpage via firefox extension

只愿长相守 提交于 2019-12-18 15:53:30

问题


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


来源:https://stackoverflow.com/questions/8373678/inject-a-css-file-into-a-webpage-via-firefox-extension

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!