Return response before http-on-examine-response

I am developing a Firefox addon, which needs to intercept the HTTP request process and return a fake response for certain URLs. This is the code I am using:

function TracingListener() {
    this.originalListener = null;

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

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

    onStopRequest: function(request, context, statusCode) {
        this.originalListener.onStopRequest(request, context, statusCode);
        var stream = Cc[";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) {
        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[";1"].getService(Ci.nsIObserverService);
observerService.addObserver(observer, "http-on-modify-request", false);
observerService.addObserver(observer, "http-on-opening-request", false);

It works fine when there is a URL response: I can change the response to "Test".

But, for some URLs which cannot be reached or are really slow, onStopRequest is never called.

I need to return a request before any real request sent, which is "http-on-open-request" or "http-on-modify-request". But at that point, Firefox refuses to accept any response because he thinks (which is true) that the response should not available.

How can I do that?



On http-on-modify-request, you should be able to call redirectTo or modify nsIChannel.URI to send the request to a data URI like data:text/plain,Test.


Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.