开发者

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"


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


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);
}


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜