When is the http-on-examine-response topic issued?

1

I'm trying to check for a 302 response in a Firefox addon using this rather common piece of observer code but the http-on-examine-response is almost never issued even on a page with a 302 redirect.

var httpRequestObserver = {
  observe: function (subject, topic, data) {
    console.log(topic)
    if (topic == 'http-on-examine-response') {
      subject.QueryInterface(Ci.nsIHttpChannel);
      try {
        this.handleRequest(subject);
      } catch(error) {
        console.error(error.message)
      }
    }
  },
  handleRequest: function(oHTTP) {
    var uri = oHTTP.URI.asciiSpec;
    console.log(oHTTP.responseStatus, uri);
  }
};
Services.obs.addObserver(httpRequestObserver, 'http-on-modify-request', false);

The only topic being issued/printed is http-on-modify-request which is useless when you want the response status. I get errors like this:

Component returned failure code: 0x80040111 (NS_ERROR_NOT_AVAILABLE) [nsIHttpChannel.responseStatus]
firefox-addon
firefox-addon-sdk
asked on Stack Overflow Aug 26, 2015 by Plakhoy

2 Answers

1

Sorry, bad copy pasta. The second argument to the addObserver method should be the topic you want to be notified on

Services.obs.addObserver(httpRequestObserver, 'http-on-examine-response', false);
answered on Stack Overflow Aug 27, 2015 by Plakhoy
0

You seem to be trying to read the response status when it's not yet available in the HTTPChannel, though that's pretty weird. It works flawlessly in my requestmod module (available on NPM), which implements an SDK-like wrapper around the HTTP channel observers and I cannot spot where your code would handle things differently.

Alternatively I would suggest using WebRequest.jsm, which is designed for usage by extensions. Specifically its onHeadersReceived listener: https://developer.mozilla.org/en-US/docs/Mozilla/JavaScript_code_modules/WebRequest.jsm#onHeadersReceived

Your code would look like this:

let { WebRequest } = require("resource://gre/modules/WebRequest.jsm");

WebRequest.onHeadersReceived.addListener(function handleRequest(response) {
  console.log(response.statusCode, response.url);
});

The only "drawback" of WebRequest.jsm is, that it doesn't work with the current stable version of Firefox, but that'll change soon...

Also note, that you should remove the listener again when your extension is unloaded - but the same rule applies for observers.

answered on Stack Overflow Sep 1, 2015 by humanoid

User contributions licensed under CC BY-SA 3.0