Tom
Tom

Reputation: 3421

How to send a POST request from a Firefox extension?

I would like to send a POST request to a web server from a firefox extension.

I have found this example to send POST requests; https://developer.mozilla.org/en/Creating_Sandboxed_HTTP_Connections#HTTP_notifications

but I can't get it to work.

I currently have code like this;

    var ioService = Components.classes["@mozilla.org/network/io-service;1"]
                              .getService(Components.interfaces.nsIIOService);
var uri = ioService.newURI("http://www.google.com", null, null);
gChannel = ioService.newChannelFromURI(uri);

postData = "a=1&b=2&c=3";

var inputStream = Components.classes["@mozilla.org/io/string-input-stream;1"]
    .createInstance(Components.interfaces.nsIStringInputStream);

inputStream.setData(postData, postData.length);

var uploadChannel = gChannel.QueryInterface(Components.interfaces.nsIUploadChannel);

uploadChannel.setUploadStream(inputStream, "application/x-www-form-urlencoded", -1);
uploadChannel.requestMethod = "POST";
uploadChannel.open();

but I get an error about "cant modify properties of a WrappedNative"

Upvotes: 1

Views: 4286

Answers (3)

intika
intika

Reputation: 9712

I use the following code to test if a URL exists:

if( typeof XMLHttpRequest == "undefined" ){
        var req = Components.classes["@mozilla.org/xmlextras/xmlhttprequest;1"]
                            .createInstance();
}
else{
        var req = new XMLHttpRequest();
}
try{
    req.open( "GET", "https://" + request.URI.host + request.URI.path );
    var timeOutID = httpNowhere._getWindow().setTimeout(function () { 
        req.abort();
        Services.prompt.alert(null,"Info","nok "+ "https://" + request.URI.host 
                                                + request.URI.path );
    }, (redirectTimer));

    req.onreadystatechange = function (e) {

            if (req.readyState==4){
                Services.prompt.alert(null,"Info","ok "+ "https://" + request.URI.host 
                                                       + request.URI.path );
                req.abort();
            }
        }
    req.send( null );

} catch (err) {
Services.prompt.alert(null,"Info",err);
}

Upvotes: 3

Neil
Neil

Reputation: 55382

requestMethod is an attribute on nsIHttpChannel so you will need to call QueryInterface on gChannel before you can set it.

Upvotes: 1

OOO
OOO

Reputation: 324

How about using XMLHttpRequest object. There is no same origin policy in extension development

Upvotes: 4

Related Questions