javascript - 在 Firefox Addon 中获取 HTTP 响应 header

标签 javascript firefox http-headers firefox-addon firefox-addon-sdk

我试图通过读取响应 header 来获取 HTTP 响应。但我无法取回任何东西。我到底缺少什么?这是我在 index.js

中的代码
var {Cc, Ci} = require("chrome");
var httpRequestObserver =
{
   init: function() {
      var observerService = Cc["@mozilla.org/observer-service;1"].getService(Ci.nsIObserverService);
      observerService.addObserver(this, "http-on-examine-response", false);
   },

  observe: function(subject, topic, data) 
  {
    if (topic == "http-on-examine-response") {
         subject.QueryInterface(Ci.nsIHttpChannel);
            this.onExamineResponse(subject);
    }
  },
onExamineResponse: function (oHttp)
  {  
        console.log("Header :"+JSON.stringify(oHttp));
        try
       {
         var header_value = oHttp.getResponseHeader("<the_header_that_i_need>"); 
         // URI is the nsIURI of the response you're looking at 
         // and spec gives you the full URL string
         var url = oHttp.URI.spec;
       }
       catch(err)
       {
         console.log(err);
       }
   }
};

httpRequestObserver.init();

我从这个 stackoverflow 和几个在线博客中获得引用:- Firefox add-on SDK: Get http response headers

Edited

我检查了控制台中的值。

  • 主题为 ()
  • 数据为空

最佳答案

做:

 oHttp = oHttp.QueryInterface(Ci.nsIHttpChannel);

onExaminResponse中,然后在getRepsonseHeader之后应该可以工作

编辑:

这对我有用:

Services.obs.removeObserver(httpRequestObserver, "http-on-examine-response", false);
var httpRequestObserver =
{
   init: function() {
      Services.obs.addObserver(this, "http-on-examine-response", false);
   },

  observe: function(subject, topic, data) 
  {
         subject = subject.QueryInterface(Ci.nsIHttpChannel);
            this.onExamineResponse(subject);
  },
onExamineResponse: function (oHttp)
  {  
        //console.log("Header :"+JSON.stringify(oHttp));
         var url = oHttp.URI.spec;
         console.log('url:', url);

        try
       {
         // URI is the nsIURI of the response you're looking at 
         // and spec gives you the full URL string
         var header_value = oHttp.getResponseHeader("X-Firefox-Spdy"); 
         console.log('header_value:', header_value);
       }
       catch(err)
       {
         if (err.name == 'NS_ERROR_NOT_AVAILABLE') {
           console.log('this http request does not have header X-Firefox-Spdy')
         } else {
          console.error(err);
         }
       }
   }
};

httpRequestObserver.init();

关于javascript - 在 Firefox Addon 中获取 HTTP 响应 header ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32854087/

相关文章:

html - CSS - 样式似乎妨碍了 Firefox 中的 URL 显示

caching - Cache-Control 的无缓存和必须重新验证之间的区别?

caching - 浏览器从缓存中提供过时的授权 header

Angular 2,Http 和不设置内容类型 "application/json"

javascript - 如何让用户能够添加另一个选择数据?

javascript - 在javascript中将单独的地址字符串序列化为一个

javascript - IE11 和 Mozilla css 转换的奇怪东西

javascript - jQuery UI .sortable .on click 移动项目并保持排序功能

javascript - 使用 YQL 和 jQuery 提取数据

javascript - 这个 `/^.*$/` 正则表达式匹配什么?