Remote Data in a Firefox Extension or Add-on
Posted on April 22nd, 2009 by Gabriel HarperDisplaying remote data in your custom Firefox toolbar makes a lot of neat things possible. If your Firefox add-on needs to fetch some data from another URL, it can be done easily with XMLHttpRequest.
Before continuing you should read more about what XMLHttpRequest is. If you are already familiar with XMLHttpRequest then it should be a breeze to start grabbing dynamic data in your Firefox extension.
If you’re new to Firefox extension development like me, navigating the MDC can take some time. The documentation is great, but a few gaps needed to be filled as well. The best place to start is to read about using XMLHttpRequest in the Mozilla Developer Center. This covers pretty much everything except retrieving the data as XML. If you’re forcing XML this is important since a few browsers stumble on plaintext data when you’re forcing XML (although most don’t).
If your request is returning a valid XML datafile, we can avoid the use of the responseText and instead get a valid XML DOM object through responseXML. Here’s a quick example:
Sample XML Response:
<?xml version="1.0" ?><root>Some data</root>
Handling the XML Response:
var xmldoc = httpRequest.responseXML; var root_node = xmldoc.getElementsByTagName('root').item(0); var node_data = root_node.firstChild.data;
The JS code above goes in the event handler for state change to 4. It simply retrieves the response as XML and gets the root tag, saving the data to node_data.
Pretty simple! Note that getElementsByTagName has a few cross-browser compatibility quirks of it’s own, so you may elect to parse through all elements in a different manner.