Firefox插件拦截并修改POST数据并获取URL

时间:2011-12-23 09:18:00

标签: javascript http firefox-addon observer-pattern

我正在尝试获取每个POST请求的URL,读取POST数据然后更改它(例如使用替换)。我的代码是抛出错误:stringStream is not defined,这是正确的,那么应该定义什么来获取setData()方法?部分代码最初来自SO帖子。另外,我如何获取它发布到的URL?

//create an nsIObserver implementor
var listener = {
   observe : function(aSubject, aTopic, aData) {
      var httpChannel = aSubject.QueryInterface(Components.interfaces.nsIHttpChannel);


          if (aTopic == "http-on-modify-request") {

            var channel= aSubject.QueryInterface(Components.interfaces.nsIHttpChannel);

            if(channel.requestMethod == "POST")
            {

                channel=channel.QueryInterface(Components.interfaces.nsIUploadChannel);  
                channel = channel.uploadStream;  
                channel.QueryInterface(Components.interfaces.nsISeekableStream)
                                .seek(Components.interfaces.nsISeekableStream.NS_SEEK_SET, 0);  
                var stream = Components.classes["@mozilla.org/binaryinputstream;1"]
                                .createInstance(Components.interfaces.nsIBinaryInputStream);  
                stream.setInputStream(channel);  
                var postBytes = stream.readByteArray(stream.available());  
                poststr = String.fromCharCode.apply(null, postBytes);  

                //change the poststr

                // poststr=poststr.replace(....);  

                // ERROR HERE - stringStream is not defined
                stringStream.setData(poststr, poststr.length);  
                //changing the postdata  
                channel = channel.QueryInterface(Components.interfaces.nsIUploadChannel);  
                channel = channel.uploadStream;  
                channel = channel.QueryInterface(Components.interfaces.nsISeekableStream)
                          .seek(Components.interfaces.nsISeekableStream.NS_SEEK_SET, 0);  
                channel.uploadStream.QueryInterface(Components.interfaces.nsIMIMEInputStream);  
                channel.uploadStream.setData(stringStream);  
                channel.requestMethod = "POST";

            }

          }

   },

   QueryInterface : function(aIID) {
      if (aIID.equals(Components.interfaces.nsISupports) ||
            aIID.equals(Components.interfaces.nsIObserver))
         return this;
      throw Components.results.NS_NOINTERFACE;
   }
};

var observerService = null;

var Init = {
   addObserver : function(){
      observerService = Components.classes["@mozilla.org/observer-service;1"].getService(Components.interfaces.nsIObserverService);
      observerService.addObserver(listener, "http-on-modify-request", false);
   },

   removeObserver : function(){
      observerService.removeObserver(listener, "http-on-modify-request");
   }
};

Init.addObserver();

1 个答案:

答案 0 :(得分:2)

请参阅Creating HTTP POSTs了解如何正确执行此操作。

  1. stringStream未在代码中的任何位置定义,因此请将var声明放在左右。
  2. inputStream.setData(postData, postData.length),请参阅nsInputStrem了解更多信息。