从chrome.webRequest.onBeforeSendHeaders提取Cookie [英] Extract cookie from chrome.webRequest.onBeforeSendHeaders

查看:4462
本文介绍了从chrome.webRequest.onBeforeSendHeaders提取Cookie的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Firefox插件来拦截HTTP请求并提取cookie。我能够从标题中提取User-agent,但无法提取cookie。我使用的代码如下。

  chrome.webRequest.onBeforeSendHeaders.addListener(function(details){
var headers = details.requestHeaders,
blockingResponse = {};

for(var i = 0,l = headers.length; i window.alert );
if(headers [i] .name =='Cookie'){
headers [i] .value ='twid = notsecret';
window.alert );
console.log(headers [i] .value);
break;
}
}

blockingResponse.requestHeaders = headers;
return blockingResponse;
},
{urls:[< all_urls>]},['requestHeaders','blocking']);

为什么这不工作,还有其他方法?

您可能是在早于49.0a版本的Firefox版本中测试:

最可能的原因是不适合你的是,你正在测试的版本早于49.0a(目前在测试版)的Firefox版本。如果是这样,当您尝试使用 window.alert()时,您的代码将会抛出一个错误。通过Firefox版本49.0a, alert()不再引发错误,但打开浏览器控制台并打印以下行(除了您尝试显示在 alert()):

 在后台窗口中不支持alert请改用console.log。 

在Firefox版本49.0a之前,您将在浏览器控制台中看到以下错误 alert()

  NS_ERROR_NOT_AVAILABLE:组件返回失败代码:0x80040111(NS_ERROR_NOT_AVAILABLE)[nsIDOMWindowUtils.isParentWindowMainWidgetVisible] nsPrompter.js:346 
未捕获异常:未知(不能转换为字符串)(未知)

在您的实例中,在您的webRequest侦听器中使用 alert()有点不同:

  NS_ERROR_NOT_AVAILABLE:组件返回失败代码:0x80040111(NS_ERROR_NOT_AVAILABLE)[nsIDOMWindowUtils.isParentWindowMainWidgetVisible ] nsPrompter.js:346 
[异常...组件返回失败代码:0x80040111(NS_ERROR_NOT_AVAILABLE)[nsIDOMWindowUtils.isParentWindowMainWidgetVisible]nsresult:0x80040111(NS_ERROR_NOT_AVAILABLE)location:JS frame :: resource:// gre / components / nsPrompter.js :: openModalWindow :: line 346data:no](unknown)

您的代码以书面形式工作:

除此之外,您的代码的工作方式与问题中的相同。但是,当您通过 console.log()输出新的cookie值时,不会验证请求头实际上是否已更改。为此,您需要在链接中的下一个事件 webRequest.onSendHeaders



验证cookie头实际已更改。已测试并验证是否在FF48.0.2 +中运行:



manifest.json

  {
description:演示更改WebRequest的cookie,
manifest_version:2,
name :change-webrequest-cookie-demo,
version:0.1,

permissions:[
webRequest,
webRequestBlocking ,
< all_urls> //必须安装Google Chrome。目前不需要Firefox。
],

background:{
scripts:[background.js]
}
}



background.json

  / *演示更改WebRequet的cookie * / 
//为测试,打开浏览器控制台
try {
// Firefox不支持警报。在FF49.0 +中,强制打开浏览器控制台。
alert('打开浏览器控制台'。
} catch(e){
// alert在49.0之前的Firefox版本中抛出一个错误
console.log('Alert抛出一个错误,可能是Firefox的版本小于49 。');
}

chrome.webRequest.onBeforeSendHeaders.addListener(function(details){
var blockingResponse = {};
//console.log(\"Checking headers );
details.requestHeaders.some(function(header){
if(header.name =='Cookie'){
console.log(Original Cookie value:+ header。 value;
header.value ='twid = notsecret';
console.log(Cookie Changed);
return true;
}
return false;
});
blockingResponse.requestHeaders = details.requestHeaders;
return blockingResponse;
},{urls:[< all_urls>]},['requestHeaders' 'blocking']);

chrome.webRequest.onSendHeaders.addListener(function(details){
details.requestHeaders.some(function(header){
if(header.name =='Cookie' ){
console.log(New Cookie value:+ header.value);
return true;
}
return false;
});
},{urls:[< all_urls>]},['requestHeaders']);



Firefox中测试和开发WebExtensions的一般说明



使用 Firefox开发版 Firefox Nightly

WebExtensions API还在开发中。什么是工作改进与每个版本的Firefox。现在,您最好使用 Firefox开发人员版本开发和测试您的WebExtension附加组件 Firefox Nightly 。您还应仔细注意要使用的功能所需的Firefox版本。此信息包含在MDN文档页面的浏览器兼容性部分中。



使用浏览器控制台

您应该使用浏览器控制台查看 console.log()从您的WebExtension后台脚本输出。如果您已经查看浏览器控制台,您将看到错误消息。你还是不得不弄清楚错误信息的含义。但是,您至少可以搜索更多内容,并包含在您的问题中


I'm working on a Firefox add-on to intercept HTTP requests and extract the cookie. I was able to extract 'User-agent' from the header but was unable to extract the cookie. The code I used is below.

chrome.webRequest.onBeforeSendHeaders.addListener(function(details){
  var headers = details.requestHeaders,
  blockingResponse = {};

  for( var i = 0, l = headers.length; i < l; ++i ) {
    window.alert("Checking headers");
    if( headers[i].name == 'Cookie' ) {
       headers[i].value = 'twid=notsecret';
       window.alert("Cookie Changed");
       console.log(headers[i].value);
       break;
    }
  }

  blockingResponse.requestHeaders = headers;
  return blockingResponse;
},
{urls: [ "<all_urls>" ]},['requestHeaders','blocking']);

Why is this not working and are there alternative methods?

解决方案

You are, probably, testing in a version Firefox earlier than version 49.0a:
The most likely reason this is not working for you is that you are testing in a Firefox version earlier than version 49.0a (which is currently in beta). If so, your code will throw an error when you try to use window.alert(). By Firefox version 49.0a, alert() no longer throws an error, but opens the Browser Console and prints the following line (in addition to the text you were attempting to show in the alert()):

alert() is not supported in background windows; please use console.log instead.

In Firefox versions prior to 49.0a you will see the following errors in the Browser Console when you try to alert():

NS_ERROR_NOT_AVAILABLE: Component returned failure code: 0x80040111 (NS_ERROR_NOT_AVAILABLE) [nsIDOMWindowUtils.isParentWindowMainWidgetVisible]                   nsPrompter.js:346
uncaught exception: unknown (can't convert to string)                                                                                                              (unknown)

In your instance, using an alert() in your webRequest listener, the error message would have been a bit different:

NS_ERROR_NOT_AVAILABLE: Component returned failure code: 0x80040111 (NS_ERROR_NOT_AVAILABLE) [nsIDOMWindowUtils.isParentWindowMainWidgetVisible]                                                                                                                                                                 nsPrompter.js:346
[Exception... "Component returned failure code: 0x80040111 (NS_ERROR_NOT_AVAILABLE) [nsIDOMWindowUtils.isParentWindowMainWidgetVisible]"  nsresult: "0x80040111 (NS_ERROR_NOT_AVAILABLE)"  location: "JS frame :: resource://gre/components/nsPrompter.js :: openModalWindow :: line 346"  data: no]             (unknown)

Your code works as written:
Other than that, your code works as written in the question. However, when you are outputting the new cookie value via console.log() does not verify that the request headers actually got changed. In order to do that, you will need to add an additional listener on the next event to fire in the chain: webRequest.onSendHeaders.

Here is some modified code that verifies the cookie header has actually been changed. It is tested and verified to be working in FF48.0.2+:

manifest.json:

{
    "description": "Demonstrate changing the cookie of a WebRequest",
    "manifest_version": 2,
    "name": "change-webrequest-cookie-demo",
    "version": "0.1",

    "permissions": [
        "webRequest",
        "webRequestBlocking",
        "<all_urls>" //Required for Google Chrome. Not, currently, needed for Firefox.
    ],

    "background": {
        "scripts": ["background.js"]
    }
}

background.json:

/*Demonstrate changing the cookie of a WebRequet */
// For testing, open the Browser Console
try{
    //Alert is not supported in Firefox. In in FF49.0+, forces the Browser Console open.
    alert('Open the Browser Console.');
}catch(e){
    //alert throws an error in Firefox versions earlier than 49.0
    console.log('Alert threw an error. Probably, the version of Firefox is less than 49.');
}

chrome.webRequest.onBeforeSendHeaders.addListener(function(details){
  var blockingResponse = {};
  //console.log("Checking headers");
  details.requestHeaders.some(function(header){
      if( header.name == 'Cookie' ) {
          console.log("Original Cookie value:" + header.value);
          header.value = 'twid=notsecret';
          console.log("Cookie Changed");
          return true;
      }
      return false;
  });
  blockingResponse.requestHeaders = details.requestHeaders;
  return blockingResponse;
}, {urls: [ "<all_urls>" ]},['requestHeaders','blocking']);

chrome.webRequest.onSendHeaders.addListener(function(details){
  details.requestHeaders.some(function(header){
      if( header.name == 'Cookie' ) {
          console.log("New Cookie value:" + header.value);
          return true;
      }
      return false;
  });
}, {urls: [ "<all_urls>" ]},['requestHeaders']);

General notes on testing and development of WebExtensions in Firefox

Use Firefox Developer Edition, or Firefox Nightly:
The WebExtensions API is very much still in development. What is working improves with each version of Firefox. For now, you are probably best off developing and testing your WebExtension add-on with Firefox Developer Edition, or Firefox Nightly. You should also make careful note of what version of Firefox is required for the functionality you desire to use. This information is contained in the "Browser compatibility" section of the MDN documentation pages.

Use the Browser Console:
You should use the Browser Console to view console.log() output from you WebExtension background scripts. If you had been viewing the Browser Console, you would have seen the error messages. You still would have had to figure out what the error messages mean. But, you would have at least had something more to search about and include in your question.

这篇关于从chrome.webRequest.onBeforeSendHeaders提取Cookie的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆