Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

firefox addon-sdk : handle http request timeout

I'm building a firefox add-on using the add-on sdk. I need to make a http request to a certain page and I want to handle the connection timeout but couldn't find anything in the api: https://addons.mozilla.org/en-US/developers/docs/sdk/latest/modules/sdk/request.html

What I'm actually looking is a callback in case the client couldn't connect to the server.

Is there a way to achieve this?

like image 443
Doua Beri Avatar asked Jan 14 '23 18:01

Doua Beri


1 Answers

The SDK request will always call onComplete, when the request is considered done for the network. This means that onComplete is called in any case, disregarding if the request returned an error or a success.

In order to detect which error you've got, you need to check the Response object's (the object passed to the onComplete function) property "status" (response.status). It holds the status code for the request. To look up status codes, consider the list on the mozilla developer network. If the response status is 0, the request has failed completely and the user is probably offline, or the target couldn't be reached.

A timeout would either be a status code 504 or 0. The implementation would be similar to this:

var Request = require("sdk/request");

Request({
  url: "http://foo.bar/request.target",
  onComplete: function(response) {
    if(response.status==0||response.status==504) {
      // do connection timeout handling
    }
    // probably check for other status codes
    else {
      // assume the request went well
    }
  }
}).get();

I personally use a validation function on the request object, which returns me a number which depends whether I've got a correct response, an error from the web server or a connection issue (4xx and 0 status codes).

like image 183
humanoid Avatar answered Jan 28 '23 10:01

humanoid