0
votes

I'm using XMLHttpRequest to exchange data between server and Firefox extension I'm developing. Unfortunately, those requests seem somehow connected with the currently open page - if I try to issue request while the current tab is closing, it will fail with an error. How can I make my requests originate from the extension itself, independently of what's going on in tabs?

EDIT: Here is the code that reproduces this problem. It's run as the main extension body (I based my design on the "Hello world" tutorial from http://kb.mozillazine.org/Getting_started_with_extension_development, so no Add-on SDK). This means that it's executed in the same place as the code from "overlay.js" in above tutorial.

function createXMLHttpRequest() {
    return Components.classes["@mozilla.org/xmlextras/xmlhttprequest;1"]
       .createInstance(Components.interfaces.nsIXMLHttpRequest);    
}

function issueRequest() {
    var req = createXMLHttpRequest();
    req.open("GET", "http://google.com", true);
    req.addEventListener("load", function(event) {
        alert("SUCCES");
    });
    req.addEventListener("error", function(event) {
        alert("ERROR");
    });
    req.send();
};

window.addEventListener("DOMContentLoaded",  function(event) {
    issueRequest();

    var doc = event.originalTarget;
    var win = doc.defaultView;

    win.addEventListener("unload", function(event) {
        issueRequest();
    });
});

This results in "SUCCESS" after opening of new tab, and "ERROR" after closing it. I would prefer to have two SUCCESSES.

1
Please show us some code - how/where do you create XMLHttpRequest? I guess that you use the Add-on SDK and do it from a content script? - Wladimir Palant
@WladimirPalant I've produced a reduced test case that shows the problem. I'm not using Add-on SDK, and this code, as far as my understanding of mentioned tutorial goes, is run as the content script. - Kim Strauss
Please check the value of win.location.href in your code - I'm pretty sure that it is the browser window, not the content page. So you are waiting for the browser window to be closed rather than a tab. - Wladimir Palant

1 Answers

1
votes

If that script is running in a browser window overlay then you attached your DOMContentLoaded handler to the wrong node - you will only get notified when the browser window itself loads. Consequently, your unload handler waits for the browser window to the closed, you probably intended to wait for a tab to be closed. The correct code would look like this:

// Wait for the browser window to load before doing anything
window.addEventListener("load", function() {
  // Attach a listener to the tabbrowser to get notified about new pages
  window.gBrowser.addEventListener("DOMContentLoaded", function(event) {
    issueRequest();

    var doc = event.originalTarget;
    var win = doc.defaultView;

    win.addEventListener("unload", function(event) {
      issueRequest();
    });
  }, false);
}, false)