在http-on-examine-response之前返回响应

时间:2013-11-19 10:33:09

标签: javascript firefox-addon xpcom

我正在开发一个Firefox插件,它需要拦截HTTP请求进程并返回某些URL的虚假响应。这是我正在使用的代码:

function TracingListener() {
    this.originalListener = null;
}

TracingListener.prototype = {
    onDataAvailable: function(request, context, inputStream, offset, count) {
        LOG("onDataAvailable");
        this.originalListener.onDataAvailable(request, context, inputStream, offset, count);
    },

    onStartRequest: function(request, context) {
        LOG("onStartRequest");
        this.originalListener.onStartRequest(request, context);
    },


    onStopRequest: function(request, context, statusCode) {
        LOG("onStopRequest");
        this.originalListener.onStopRequest(request, context, statusCode);
        var stream = Cc["@mozilla.org/io/string-input-stream;1"].createInstance(Ci.nsIStringInputStream);
        stream.setData("Test", -1);
        this.originalListener.onStopRequest(request, context, Components.results.NS_OK);

    },

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

var observer = {
    observe: function(subject, topic, data) {
        LOG(topic);
        var httpChannel = subject.QueryInterface(Ci.nsIHttpChannel);
        var url = httpChannel.URI.spec;
        LOG("Test:" + url);
        if (!pattern.test(url)) return;

        if (topic == 'http-on-modify-request') {
            var newListener = new TracingListener();
            newListener.originalListener = httpChannel.setNewListener(newListener);

            } else if (topic == "http-on-examine-response" || topic == "http-on-examine-cached-response" || topic == "http-on-examine-merged-response") {
            var newListener = new TracingListener();
            newListener.originalListener = httpChannel.setNewListener(newListener);
        }
    }
};


var observerService = Cc["@mozilla.org/observer-service;1"].getService(Ci.nsIObserverService);
observerService.addObserver(observer, "http-on-modify-request", false);
observerService.addObserver(observer, "http-on-opening-request", false);

当有URL响应时,它可以正常工作:我可以将响应更改为“Test”。

但是,对于某些无法访问或非常慢的URL,永远不会调用onStopRequest

我需要在发送任何实际请求之前返回请求,即“http-on-open-request”或“http-on-modify-request”。但在那时,Firefox拒绝接受任何回复,因为他认为(这是真的)响应不应该可用。

我该怎么做?

1 个答案:

答案 0 :(得分:10)

http-on-modify-request,您应该可以致电redirectTo或修改nsIChannel.URI,将请求发送到data:text/plain,Test等数据URI。