我以使用这种方法结束。它是通过反复试验编码的,因此在某些情况下可能是错误的,但我没有注意到许多测试有任何问题。
// opens aUrl in aBrowser and call an action defined in aCallback immediately after window is prepared
function loadInBrowserWithCallback (aBrowser, aUrl, /* function(window) */ aCallback) {
var loadedUrl = nsIIOService.newURI(aUrl, null, null).spec // canonify chrome url (what mean 'canonifing': https://developer.mozilla.org/en-US/docs/XPCOM_Interface_Reference/nsIChromeRegistry#canonify%28%29 )
var lastWindow = aBrowser.contentWindow;
lastWindow.__thisIsPrevWin = true;
var progressListener = {
onLocationChange : function(aWebProgress, aRequest, aLocation, aFlags) {
var window = aWebProgress.DOMWindow;
if(!window.__thisIsPrevWin && window.location.href === loadedUrl) {
// the property assigned to previus window was removed and location.href isn't any transitional url
aBrowser.removeProgressListener(this);
aCallback(window);
}
},
onProgressChange: function(aWebProgress, aRequest, aCurSelfProgress, aMaxSelfProgress, aCurTotalProgress, aMaxTotalProgress) {
var window = aWebProgress.DOMWindow;
if(!window.__thisIsPrevWin && window.location.href === loadedUrl) {
aBrowser.removeProgressListener(this);
aCallback(window);
}
},
onSecurityChange: function(aWebProgress, aRequest, aState) {
var window = aWebProgress.DOMWindow;
if(!window.__thisIsPrevWin && window.location.href === loadedUrl) {
aBrowser.removeProgressListener(this);
aCallback(window);
}
},
onStateChange: function(aWebProgress, aRequest, aStateFlags, aStatus) {
var window = aWebProgress.DOMWindow;
if(!window.__thisIsPrevWin && window.location.href === loadedUrl) {
aBrowser.removeProgressListener(this);
aCallback(window);
}
},
onStatusChange: function(aWebProgress, aRequest, aStatus, aMessage) {
var window = aWebProgress.DOMWindow;
if(!window.__thisIsPrevWin && window.location.href === loadedUrl) {
aCallback(window);
aBrowser.removeProgressListener(this);
}
},
QueryInterface: function(aIID) {
if (aIID.equals(Ci.nsIWebProgressListener) ||
aIID.equals(Ci.nsISupportsWeakReference) ||
aIID.equals(Ci.nsISupports))
return this;
throw Cr.NS_NOINTERFACE;
}
};
aBrowser.addProgressListener(progressListener, Ci.nsIWebProgress.NOTIFY_ALL);
aBrowser.loadURI(aUrl);
};