gpt4 book ai didi

javascript - 在 Firefox 中检测页面加载完成事件

转载 作者:塔克拉玛干 更新时间:2023-11-02 21:22:43 25 4
gpt4 key购买 nike

我正在编写一个 Firefox 附加组件,在网页完全加载后执行某些操作。
我当前的代码是

var target = this;
const STATE_STOP = Components.interfaces.nsIWebProgressListener.STATE_STOP;
const STATE_IS_WINDOW = Components.interfaces.nsIWebProgressListener.STATE_IS_WINDOW;
const STATE_IS_DOCUMENT = Components.interfaces.nsIWebProgressListener.STATE_IS_DOCUMENT;
const locationChangeListener = {
onStatusChange: function(){},
onProgressChange: function(){},
onLocationChange: function(aWebProgress, aRequest, aLocation){},
onStateChange: function(aWebProgress, aRequest, aFlag, aStatus){
if((aFlag & STATE_STOP) && (aFlag & STATE_IS_WINDOW)){


//Do something in here


}
},
onSecurityChange: function(){}
};
gBrowser.addProgressListener(locationChangeListener);

它工作正常。但有时,例如使用 AJAX 调用的网页,此事件会在一个网页上触发多次。

有什么方法可以检测网页是否加载完成?

最佳答案

如果您只对检测页面何时完全加载而不是中间步骤感兴趣,则可以更轻松地监听加载事件,例如(来自 https://developer.mozilla.org/en/Code_snippets/Tabbed_browser 的代码):

function examplePageLoad(event) {
if (event.originalTarget instanceof HTMLDocument) {
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);
...

gBrowser 是主 firefox 窗口中的全局变量(如果您的代码从 browser.xul 的覆盖层运行,您应该会看到它)。如果没有(例如在侧边栏中运行),您可以获得对主窗口的引用:

var mainWindow = window.QueryInterface(Components.interfaces.nsIInterfaceRequestor)
.getInterface(Components.interfaces.nsIWebNavigation)
.QueryInterface(Components.interfaces.nsIDocShellTreeItem)
.rootTreeItem
.QueryInterface(Components.interfaces.nsIInterfaceRequestor)
.getInterface(Components.interfaces.nsIDOMWindow);

mainWindow.gBrowser.addEventListener (...)

关于javascript - 在 Firefox 中检测页面加载完成事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2771188/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com