Chrome API responseHeaders

时间:2013-04-09 01:30:15

标签: google-chrome google-chrome-extension

基于此文档:https://developer.chrome.com/extensions/webRequest.html#event-onHeadersReceived

我试图通过控制台显示响应,如:

console.log(info.responseHeaders);

但它返回undefined

但这有效:

console.log("Type: " + info.type);

请帮助,我真的需要获取responseHeaders数据。

1 个答案:

答案 0 :(得分:15)

您必须像这样请求响应标头:

chrome.webRequest.onHeadersReceived.addListener(function(details){
  console.log(details.responseHeaders);
},
{urls: ["http://*/*"]},["responseHeaders"]);

使用示例。这是我在扩展中使用webRequest api的一个实例。 (仅显示部分不完整的代码)

我需要间接访问一些服务器数据,我通过使用302重定向页面来实现。我发送Head请求到所需的网址,如下所示:

$.ajax({
  url: url,
  type: "HEAD"
  success: function(data,status,jqXHR){
    //If this was not a HEAD request, `data` would contain the response
    //But in my case all I need are the headers so `data` is empty
    comparePosts(jqXHR.getResponseHeader('redirUrl')); //where I handle the data
  }     
});

然后我使用location api为我自己的用途抓取webRequest标题时默默地终止重定向:

chrome.webRequest.onHeadersReceived.addListener(function(details){
  if(details.method == "HEAD"){
    var redirUrl;
    details.responseHeaders.forEach(function(v,i,a){
      if(v.name == "Location"){
       redirUrl = v.value;
       details.responseHeaders.splice(i,1);
      }
    });
    details.responseHeaders.push({name:"redirUrl",value:redirUrl});
    return {responseHeaders:details.responseHeaders}; //I kill the redirect
  }
},
{urls: ["http://*/*"]},["responseHeaders","blocking"]);

我实际上处理了onHeadersReceived侦听器中的数据,但这种方式显示了响应数据的位置。