views:

183

answers:

2

I'm trying to get a Firefox plugin to read data from a HTTP get, parse the results and present them as links in a bookmark-like drop-down menu.

My quesion then is: Does anyone have any sample code that will do this?

+2  A: 

Having never developed a plugin myself, I'm not certain how this is typically done in plugins, but since plugin scripting is JavaScript, I can probably help out with the loading part. Assuming a variable named url containing the URL you want to request:

var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", url, true);

xmlhttp.onreadystatechange = function() {
    if(this.readyState == 4) { // Done loading?
        if(this.status == 200) { // Everything okay?
            // read content from this.responseXML or this.responseText
        } else { // Error occurred; handle it
            alert("Error " + this.status + ":\n" + this.statusText);
        }
    }
};

xmlhttp.send(null);

A couple of notes notes on this code:

  • You may want more sophisticated status code handling. For example, 200 is not the only non-error status code. Details on status codes can be found here.
  • You probably want to have a timeout to handle the case where, for some reason, you don't get to readyState 4 in a reasonable amount of time.
  • You may want to do things when earlier readyStates are received. This page documents the readyState codes, along with other properties and methods on the XMLHttpRequest object which you may find useful.
Robert J. Walker
A: 
pc1oad1etter
Actually, since the onreadystate function I wrote assumed the XMLHttpRequest object as its context, you would want to use this.responseText or this.responseXML, as I indicated in the comment in the code.
Robert J. Walker