问题描述
我可以使用哪些事件侦听器来标识来自firefox插件中的hiddenDOMWindow(或其中的iframe)的请求?例如,在"http-on-modify-request"事件中发送请求之前,我需要执行此操作.
What event-listeners can I use to identify requests originating from the hiddenDOMWindow (or an iframe within it) in a firefox-addon? I need to do this BEFORE the request has been sent, in the "http-on-modify-request" event, for example.
我尝试过的事情:
- 注册全局"http-on-modify-request";但我无法区分源窗口
- 将侦听器添加到hiddenDOMWindow本身;但我找不到任何加载前事件
- 将侦听器添加到hiddenDOMWindow.document;没有加载前事件
- 将侦听器添加到已创建的hiddenDOMWindow.document.iframe中;没有加载前事件
推荐答案
首先,您需要从nsIChannel
获取DOMWindow
:
function getDOMWindowFromChannel(ch) {
var wp;
try {
if (ch.loadGroup && ch.loadGroup.groupObserver) {
wp = ch.loadGroup.groupObserver.
QueryInterface(Ci.nsIWebProgress);
}
} catch (ex) {}
try {
if (!wp) {
wp = ch.notificationCallbacks.
getInterface(Ci.nsIWebProgress);
}
}
catch (ex) {}
try {
if (wp) {
return wp.DOMWindow || null;
}
}
catch (ex) {}
return null;
}
现在您有了一个DOMWindow
,您需要找到该DOMWindow
的顶层窗口,这并不是很直观:
Now that you got a DOMWindow
, you need to find the top level window for that DOMWindow
, which is not really intuitive:
function getToplevelWindow(win) {
try {
return win.QueryInterface(Ci.nsIInterfaceRequestor).
getInterface(Ci.nsIWebNavigation).
QueryInterface(Ci.nsIDocShell).
treeOwner.
QueryInterface(Ci.nsIInterfaceRequestor).
getInterface(Ci.nsIXULWindow).
docShell.
contentViewer.DOMDocument.defaultView;
}
catch (ex) {
// Likely already a top-level window.
return win;
}
}
现在,让我们来制作和安装观察器,将它们组合在一起:
Now, lets craft and install the observer, bringing all together:
function observe(channel, topic, data) {
if (!(channel instanceof Ci.nsIChannel)) {
return;
}
var win = getDOMWindowFromChannel(channel);
if (!win) {
return;
}
var topWin = getToplevelWindow(win);
if (topWin.location.href.indexOf("chrome://browser/content/hiddenWindow") != 0) {
return;
}
// do stuff, e.g.
console.log(topWin.location.href);
}
Services.obs.addObserver(observe, "http-on-modify-request", false);
应该注意的是,并不是所有的请求都是nsIChannel
,并不是所有的nsIChannel
实际上都有关联的DOMWindow
或实际的loadGroup
(例如,后台请求),因此是所有这些try catch
块.
It should be noted that not all requests are nsIChannel
and not all nsIChannel
actually have a DOMWindow
or real loadGroup
associated (e.g. background requests), hence all those try catch
blocks.
此外,别忘了在某个时候再次删除观察者,而我已经跳过了. ;)
Also, don't forget to remove the observer again at some point, which I skipped. ;)
最后,这是一些实际测试此代码的代码(我在about:newtab选项卡上以Scratchpad的身份运行了整个程序,该选项卡恰好具有附加组件的chrome特权):
And lastly, here is some code to actually test this (I ran the whole thing as a Scratchpad on an about:newtab tab, which happens to have chrome privileges just like add-ons):
var hw = Services.appShell.hiddenDOMWindow;
var iframe = hw.document.createElement("iframe");
hw.document.documentElement.appendChild(iframe);
var r = iframe.contentWindow.XMLHttpRequest();
r.open("GET", "http://example.org/");
r.send();
这篇关于如何识别源自"hiddenDOMWindow"的请求?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!