我尝试过:window.addEventListener("load", function(){}, true)
和content.document.defaultView.addEventListener("load", function(){}, true)
,但两人都无法工作。
答案 0 :(得分:1)
引用tabbrowser snippets example逐字引用(请参阅我对上一个问题的回答):
function examplePageLoad(event) {
if (event.originalTarget instanceof Components.interfaces.nsIDOMHTMLDocument) {
var win = event.originalTarget.defaultView;
if (win.frameElement) {
// Frame within a tab was loaded. win should be the top window of
// the frameset. If you don't want do anything when frames/iframes
// are loaded in this web page, uncomment the following line:
// return;
// Find the root document:
win = win.top;
}
}
}
// do not try to add a callback until the browser window has
// been initialised. We add a callback to the tabbed browser
// when the browser's window gets loaded.
window.addEventListener("load", function () {
// Add a callback to be run every time a document loads.
// note that this includes frames/iframes within the document
gBrowser.addEventListener("load", examplePageLoad, true);
}, false);
...
// When no longer needed
gBrowser.removeEventListener("load", examplePageLoad, true);
...
window.addEventListener
)。gBrowser.addEventListener
)中添加页面加载的事件监听器。到目前为止,非常好......
现在,我们需要丢弃不是当前文档/选项卡的所有事件。我们只需将.originalTarget
与content.document
进行比较。
这里的代码基本上与上面的代码相同(并且更短):
window.addEventListener("load", function () {
gBrowser.addEventListener("load", function(event) {
if (event.originalTarget != content.document) {
return;
}
// XXX do something
}, true);
}, false);
如果需要,您可能不仅希望实现load
的监听器,还希望实现pageshow
的监听器。
然而,有一种替代方案,可以省略检查(如"On page load"中所述)。 IIRC有一些问题,所以我不推荐它,你还需要过滤掉非文档加载(图像等)。