I'm developing a standalone XULRunner application, in which its important to give a user feedback on what is happening when a page is loading. My first implementation was guided by the MDN tutorial. However, this could only work with pages that I open from my code. I had no way of giving a user feedback for links in the body of a document. Further search landed me at a forum thread. Following what this guy did, I could listen to page loading events including state changes, progress changes, and URL location changes. I can now tell when a page starts to load so that I can display the progress bar. I can also tell when the page is fully loaded so that I can hide the progress bar. My code is as shown below:
var myExt_urlBarListener = {
QueryInterface: function(aIID)
{
if (aIID.equals(Components.interfaces.nsIWebProgressListener) ||
aIID.equals(Components.interfaces.nsISupportsWeakReference) ||
aIID.equals(Components.interfaces.nsISupports))
return this;
throw Components.results.NS_NOINTERFACE;
},
onLocationChange: function(aProgress, aRequest, aURI)
{
myExtension.processNewURL(aURI);
},
//onStateChange: function(a, b, c, d) {},
onStateChange: function(aProgress, aRequest, aFlag, aStatus) {
const STATE_START = Components.interfaces.nsIWebProgressListener.STATE_START;
const STATE_STOP = Components.interfaces.nsIWebProgressListener.STATE_STOP;
if(aFlag & STATE_START) {
document.getElementById("progressBar").hidden = false;
}
if(aFlag & STATE_STOP) {
document.getElementById("progressBar").hidden = true;
}
return 0;
},
onProgressChange: function(a, b, c, d, e, f) { return 0; },
onStatusChange: function(a, b, c, d) { return 0; },
onSecurityChange: function(a, b, c) { return 0; }
};
var myExtension = {
oldURL: null,
init: function() {
// Listen for webpage loads
document.getElementById("browser-id").addProgressListener(myExt_urlBarListener,
Components.interfaces.nsIWebProgress.NOTIFY_STATE_DOCUMENT);
},
uninit: function() {
document.getElementById("browser-id")
.removeProgressListener(myExt_urlBarListener);
},
processNewURL: function(aURI) {
if (aURI.spec == this.oldURL)
return;
// alert(aURI.spec);
document.getElementById("statusBar").setAttribute("label", aURI.spec);
// document.getElementById("progressBar").hidden = false;
this.oldURL = aURI.spec;
}
};
window.addEventListener("load", function() {myExtension.init()}, false);
window.addEventListener("unload", function() {myExtension.uninit()}, false);
I'm wondering if there's a better way of doing this.
No, using progress listeners is the way to go - that's what Firefox is using to display you status changes while a page is loading. However, I recommend using XPCOMUtils.jsm
module to simplify your QueryInterface
implementation:
Components.utils.import("resource://gre/modules/XPCOMUtils.jsm");
...
QueryInterface: XPCOMUtils.generateQI([Components.interfaces.nsIWebProgressListener,
Components.interfaces.nsISupportsWeakReference]),