Chrome API responseHeaders

mad*_*koy 5 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数据.

Bea*_*ist 16

你必须像这样请求响应头:

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

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

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

$.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
  }     
});
Run Code Online (Sandbox Code Playgroud)

然后我location使用webRequestapi 在为我自己的用途抓取标题时默默地杀死重定向:

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"]);
Run Code Online (Sandbox Code Playgroud)

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