Tua*_*-Vu 5 javascript events dom firefox-addon
我正在编写一个 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);
Run Code Online (Sandbox Code Playgroud)
它工作正常。但有时,例如带有 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);
...
Run Code Online (Sandbox Code Playgroud)
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 (...)
Run Code Online (Sandbox Code Playgroud)