在Firefox扩展程序中,我试图通过插入DOM元素将表单添加到网页中,然后处理用户在表单中输入的任何数据。
我尝试过多种方法,但无法将表单插入网页document
。我尝试使用不同类型的附加组件,Overlay(XUL)和Add-on SDK,但我无法让它工作。
var html = sth;
$("body").html(html);
$('.id_of_ele').html('I want to show');
unsafeWindow.document
,但我认为这是一个非常糟糕的主意,代码看起来非常糟糕。如何从Firefox扩展程序访问网页的document
?
答案 0 :(得分:1)
如果您正在寻找已知工作代码的示例,您始终可以download one or more extensions from Mozilla Add-ons执行与您想要完成的工作相近的工作,并了解他们是如何做到这一点的。显然,您应该查看许可证(在每个扩展页面上链接)以查看代码的合法状态。那里有成千上万的工作实例。其中绝大多数代码的许可方式允许您重复使用它。
您尝试使用的jQuery访问依赖于指向您要修改的文档的document
变量。在您运行的上下文中,Firefox加载项,document
变量默认情况下可以指向您感兴趣或根本不定义的网页的祖先的文档。 document
实际上取决于调用附加代码的上下文。在Firefox附加组件中,默认情况下,document
变量几乎从不指向网页的内容。您必须记住,您编写的代码旨在运行在 更大的上下文(整个浏览器/用户代理)中,而不是用于网页上的内容脚本(上下文中的上下文)浏览器仅限于运行脚本的网页内容,或者从源自页面内的引用获取的数据。)
获取当前所选标签文档的访问权限:
更改内容文档非常简单。您可以像使用任何JavaScript一样更改它。您可能会感到沮丧的问题是获得对该文档的引用。
Firefox overlay和restartless/bootstrapped在整个浏览器上拥有强大的功能。但是,上下文以及window
指向的内容,或者即使它被定义,也在很大程度上取决于JavaScript的调用方式。这既令人困惑又令人沮丧。在MDN上,有一个文件" Working with windows in chrome code"其中描述了许多问题。
从扩展程序中,您可以访问所有窗口和标签页。但是,您可能想要的只是一些可以帮助您访问当前所选文档的代码。
这应该适用于所有上下文,以便为您提供当前所选选项卡的文档引用:
var selectedTabWindow = Components.classes["@mozilla.org/appshell/window-mediator;1"]
.getService(Components.interfaces.nsIWindowMediator)
.getMostRecentWindow("navigator:browser");
var selectedTabDocument = selectedTabWindow.content.document;
如果您要从内容脚本转换代码,而该代码只需要查找window
和document
个对象,您可以编写如下内容:
if (typeof window === "undefined") {
var window;
} else {
//Keep a reference to whatever was defined as window.
var originalWindow = window;
}
//Get the window from the most recently selected tab.
window = Components.classes["@mozilla.org/appshell/window-mediator;1"]
.getService(Components.interfaces.nsIWindowMediator)
.getMostRecentWindow("navigator:browser");
//Now that we have a window for the most recently selected tab,
// get the document for it.
if (typeof document === "undefined") {
var document;
} else {
//Keep a reference to whatever was defined as document.
var originalDocument = document;
}
document = window.content.document;
//Now that we have a window for the most recently selected tab,
// get the gBrowser for it.
if (typeof gBrowser === "undefined") {
var gBrowser;
} else {
//Keep a reference to whatever was defined as gBrowser.
var originalGBrowser = gBrowser;
}
gBrowser = window.gBrowser;
显然,上述内容将覆盖当前定义为window
,document
和gBrowser
的当前变量。根据您运行的上下文以及您定义这些内容的范围,这可能是一件好事,或者更改该引用可能是个坏主意。例如,如果代码在弹出窗口中运行,则window
是对弹出窗口的引用。在这种情况下,您可以获得对打开弹出窗口的窗口的引用:
var windowWhichOpendedThisOne = window.opener;
var documentForWindowWhichOpendedThisOne = window.opener.content.document;
如果您在事件处理程序中,则可以从以下位置获取事件目标的窗口:
var windowInWhichEventTargetExists = event.view;
根据网址选择要执行的操作:
一旦你有了正确的document
,根据文档的网址选择做什么应该很容易:
var currentUrl = document.location.href;