扩展firefox中的Post标头

Post header in extension firefox

本文关键字:标头 Post 中的 firefox 扩展      更新时间:2023-09-26

我正在构建一个扩展,在这里我可以捕获所有的post请求。但是在httpChannel.originalURI.spec中没有任何来自帖子的属性。我怎样才能得到这篇文章的摘要?

myObserver.prototype = {
 observe: function(subject, topic, data) {
  if("http-on-modify-request"){
    var httpChannel = subject.QueryInterface(Components.interfaces.nsIHttpChannel);
    if(httpChannel.requestMethod=="POST")
      alert(httpChannel.originalURI.spec);
       }
  }
},
register: function() {
var observerService = Components.classes["@mozilla.org/observer-service;1"]
                      .getService(Components.interfaces.nsIObserverService);
observerService.addObserver(this, "http-on-modify-request", false);
},
unregister: function() {
var observerService = Components.classes["@mozilla.org/observer-service;1"]
                        .getService(Components.interfaces.nsIObserverService);
observerService.removeObserver(this, "http-on-modify-request");
}
}

有什么想法吗?

nsIHttpChannel仅提供对HTTP标头的访问。POST数据是作为请求主体的一部分发送的,因此您需要将对象接口更改为nsIUploadChannel,并将二进制上传数据读取为字符串。

var uploadChannel = httpChannel.QueryInterface(Ci.nsIUploadChannel);
var uploadStream = uploadChannel.uploadStream;
uploadStream.QueryInterface(Ci.nsISeekableStream).
             seek(Ci.nsISeekableStream.NS_SEEK_SET, 0);
var binStream = Cc["@mozilla.org/binaryinputstream;1"].
                createInstance(Ci.nsIBinaryInputStream);
binStream.setInputStream(uploadStream);
var postBytes = binStream.readByteArray(binStream.available());
var postString = String.fromCharCode.apply(null, postBytes);

Luckyrat的代码对我来说工作不正常。我不得不处理一些超时的请求。注意到nmairs注释此代码工作正常(据我所知):

function getPostString(httpChannel) {
    var postStr = "";
    try {
        var uploadChannel = httpChannel.QueryInterface(Ci.nsIUploadChannel);
        var uploadChannelStream = uploadChannel.uploadStream;
        if (!(uploadChannelStream instanceof Ci.nsIMultiplexInputStream)) {
            uploadChannelStream.QueryInterface(Ci.nsISeekableStream).seek(Ci.nsISeekableStream.NS_SEEK_SET, 0);
            var stream = Cc["@mozilla.org/binaryinputstream;1"].createInstance(Ci.nsIBinaryInputStream);
            stream.setInputStream(uploadChannelStream);
            var postBytes = stream.readByteArray(stream.available());
            uploadChannelStream.QueryInterface(Ci.nsISeekableStream).seek(0, 0);
            postStr = String.fromCharCode.apply(null, postBytes);
        }
    }
    catch (e) {
        console.error("Error while reading post string from channel: ", e);
    }
    finally {
        return postStr;
    }
}