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) {
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);
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With