Firefox 附加组件获取发出 HTTP 请求的 DOM window

Firefox add-on get the DOM window which made an HTTP request

我正在 Firefox Add-on SDK 扩展中捕获 HTTP 请求。我需要获取与请求关联的 DOM window。但是,我收到 NS_NOINTERFACE 错误。

这是我的代码:

  var httpRequestObserver = {
    observe: function (subject, topic, data) {
      var httpRequest = subject.QueryInterface(Ci.nsIHttpChannel);
      var requestUrl = subject.URI.host;
      var domWin;
      var assWindow;
      console.log('URL: ', requestUrl);
      try {
        domWin = httpRequest.notificationCallbacks.getInterface(Ci.nsIDOMWindow);
        assWindow = httpChannel.notificationCallbacks.getInterface(Ci.nsILoadContext)
                               .associatedWindow;
        console.log(domWin);
      } catch (e) {
        console.log(e);
      }
      // console.log('TAB: ', tabsLib.getTabForWindow(domWin.top));

      var hostName = wn.domWindow.getBrowser().selectedBrowser.contentWindow.location.host;
      console.log('HOST: ', hostName);
    },

    get observerService() {
      return Cc['@mozilla.org/observer-service;1'].getService(Ci.nsIObserverService);
    },

    register: function () {
      this.observerService.addObserver(this, 'http-on-modify-request', false);
    },

    unregister: function () {
      this.observerService.removeObserver(this, 'http-on-modify-request');
    }
  };

  httpRequestObserver.register();

我已经尝试了 nsIDOMWindownsILoadContext,但是在尝试获取 window 对象时总是出现 NS_NOINTERFACE 错误。

我终于通过

获得了我需要的数据
httpRequest.notificationCallbacks.getInterface(Ci.nsILoadContext).topFrameElement

例如,要获取启动请求的文档的url,我使用了

httpRequest.notificationCallbacks.getInterface(Ci.nsILoadContext).topFrameElement._documentURI.href

由于您已经找到了如何从请求中获取 <browser>,因此您可以执行以下操作以返回 SDK API:

let browser = ....topFrameElement
let xulTab = browser.ownerDocument.defaultView.gBrowser.getTabForBrowser(browser)
let sdkTab = modelFor(xulTab)

modelFor() 记录在选项卡模块中。