Firefox插件获取了发出HTTP请求的DOM窗口

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

本文关键字:请求 DOM 窗口 HTTP 插件 获取 Firefox      更新时间:2023-09-26

我正在Firefox插件SDK扩展中捕获HTTP请求。我需要获取与请求相关联的DOM窗口。但是,我得到了一个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()记录在选项卡模块中。