Sunday, September 30, 2007

Getting browser's progress status

Ever wonder how to correctly get the page's progress of the browser (loading, transferring, waiting, etc)? Well here it is:

There are several states that can be detected using this interface
  • onStateChange
  • onLocationChange
  • onProgressChange
  • onStatusChange
  • onSecurityChange
  • onLinkIconAvailable
even though their names can seem self-explanatory, you better check the full documentation.

1) create an object that will withhold the Progress Listener Interface

var oProgressListener = new Object(); //on top of all codes, or with global scope


2) get the Progress Listener interface and assign preliminary values.

wpl = Components.interfaces.nsIWebProgressListener;

//I'm still not very sure what this function does :D
oProgressListener.QueryInterface = function(aIID) {
if (aIID.equals(oProgressListener.wpl) ||
aIID.equals(Components.interfaces.nsISupportsWeakReference) ||
aIID.equals(Components.interfaces.nsISupports)) return this;
throw Components.results.NS_NOINTERFACE;

}


3) assign appropriate functions to the state you wants to:

//detect URL changes
oProgressListener.onLocationChange = function(aProgress, aRequest, aURI) {

alert('my URL was changed');
return 0;

}

//detect the starting of loading a new page / document
oProgressListener.onStateChange = function(aProgress, aRequest, aFlag, aStatus) {
if (aFlag & oProgressListener.wpl.STATE_IS_DOCUMENT){
alert('New page is being loaded');
}
}

//detect when a page is fully loaded
if (aFlag & oProgressListener.wpl.STATE_STOP) {
if ( aFlag & oProgressListener.wpl.STATE_IS_DOCUMENT ) {
alert('New page has finished loading');
}
}


4) Associate the progress listener for a "browser" to a listener object

browser.addProgressListener( oProgressListener,
Components.interfaces.nsIWebProgress.NOTIFY_STATE_WINDOW);

No comments: