从firefox扩展发送POST请求

时间:2011-02-10 06:53:42

标签: javascript firefox firefox-addon

我想从firefox扩展程序向Web服务器发送POST请求。

我发现这个例子发送POST请求; https://developer.mozilla.org/en/Creating_Sandboxed_HTTP_Connections#HTTP_notifications

但我无法让它发挥作用。

我目前有这样的代码;

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

但我收到有关“无法修改WrappedNative属性”的错误

3 个答案:

答案 0 :(得分:4)

如何使用XMLHttpRequest对象。 扩展开发中没有相同的原始策略

答案 1 :(得分:3)

我使用以下代码来测试是否存在URL:

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

答案 2 :(得分:1)

requestMethod是nsIHttpChannel上的一个属性,因此您需要先在gChannel上调用QueryInterface,然后才能进行设置。