Search code examples
javascriptfirefox-addon-sdk

Firefox SDK doing a request more than once


I am doing a server request with my firefox sdk, which replies a XML file.

I am parsing the XML file for two special values and put them into a global array (in my onComplete function).

My Problem is that the array does not save the values in element 0 and 1 and I don't know why!

My second Problem is that I want to call a request in my addon for the current tab url (that means more than one time). I know the request module says "Each Request object is designed to be used once" but is it possible to call it more than once?

I always get this error :

Error: This request object has been used already. You must create a new one to make a new request.

var Request = require("request").Request;
var {Cc, Ci} = require("chrome");
var parser = Cc["@mozilla.org/xmlextras/domparser;1"].createInstance(Ci.nsIDOMParser);
var setURL = "example.org";
var exampleArray = new Array();

function parseResponse(response) {  
    var xml = parser.parseFromString(response.text, "application/xml");  
    exampleArray[0] = xml.getElementsByTagName("example")[0].getAttribute("example"); // integer value
    exampleArray[1] = xml.getElementsByTagName("example2")[0].getAttribute("example2"); //integer value
 }

var exampleRequest = Request({
      url: "http://www.example.com",
      onComplete: parseResponse, 
})
exampleRequest.get();

console.log("exampleArray" + exampleArray.length); //always 0

Thanks


Solution

  • Just wrap your request call in a function that's reusable. Request is a constructor, so you can instantiate several requests. But each request can only request one URL.

    function request (url) {
      Request({
        url: url
        onComplete: parseResponse, 
      }).get();
    }
    

    For the XML issue, just console log the individual nodes, probably not what you expect somewhere.