24

拡張機能に chrome.webRequest API を実装しようとしていますが、何らかの理由で何をしても機能しません。誰かが使用例を投稿できますか? または私の間違いを修正しますか?基本的に私がやろうとしているのは、受信したヘッダーを応答から傍受することです。

これは onBeforeSendHeaders の実装ですが、OnHeadersRecieved も使用したいと思います。

var requestFilter = {
    urls: [ "<all_urls>" ]
  },
  // The 'extraInfoSpec' parameter modifies how Chrome calls your
  // listener function. 'requestHeaders' ensures that the 'details'
  // object has a key called 'requestHeaders' containing the headers,
  // and 'blocking' ensures that the object your function returns is
  // used to overwrite the headers
  extraInfoSpec = ['requestHeaders','blocking'],
  // Chrome will call your listener function in response to every
  // HTTP request
  handler = function( details ) {
    alert(details);
    var headers = details.requestHeaders,
      blockingResponse = {};

    // Each header parameter is stored in an array. Since Chrome
    // makes no guarantee about the contents/order of this array,
    // you'll have to iterate through it to find for the
    // 'User-Agent' element
    for( var i = 0, l = headers.length; i < l; ++i ) {
      if( headers[i].name == 'User-Agent' ) {
        headers[i].value = '>>> Your new user agent string here <<<';
        break;
      }
      // If you want to modify other headers, this is the place to
      // do it. Either remove the 'break;' statement and add in more
      // conditionals or use a 'switch' statement on 'headers[i].name'
    }

    blockingResponse.requestHeaders = headers;
    return blockingResponse;
  };

chrome.webRequest.onBeforeSendHeaders.addListener( handler, requestFilter, extraInfoSpec );

これは私のマニフェストファイルです:

    {
   "background_page": "iRBackground.html",
   "browser_action": {
      "default_icon": "Off.png",
      "popup": "iRMenu.html"
   },
   "content_scripts": [ {
      "js": [ "Content.js" ],
      "matches": [ "http://*/*" ],
      "run_at": "document_start"
   } ],
   "description": "***",
   "icons": {
      "128": "On128x128.png",
      "16": "On.png",
      "48": "On48x48.png"
   },
   "key": "****",
   "manifest_version": 2,
   "name": "***",
   "permissions": [ "tabs", "notifications", "unlimitedStorage", "webRequest", “webRequestBlocking”, “&lt;all_urls>”],
   "update_url": "***/Chrome/UpdateVersion.xml",
   "version": "1.3"
}

Chromeから得られるエラーは次のとおりです。Uncaught TypeError: Cannot read property 'onBeforeSendHeaders' of undefined

誰かが何か間違っているのを見ますか??? ありがとう

4

4 に答える 4

35

使用例として、この作業コードを提供できます。他の方法は逆に思えるので、このように書きましたが、それは私の個人的な好みであり、どちらも同じように機能するはずです。

マニフェスト

{
  "name": "Chrome webrequest test",
  "version": "0.1",
  "description": "A test for webrequest",
  "manifest_version": 2,
  "permissions": [
    "<all_urls>","webRequest","webRequestBlocking"
  ],
  "background": {
    "scripts": ["bgp.js"],
    "persistent": true
  }
}

bgp.js

chrome.webRequest.onBeforeSendHeaders.addListener(function(details){
  //console.log(JSON.stringify(details));
  var headers = details.requestHeaders,
  blockingResponse = {};

  // Each header parameter is stored in an array. Since Chrome
  // makes no guarantee about the contents/order of this array,
  // you'll have to iterate through it to find for the
  // 'User-Agent' element
  for( var i = 0, l = headers.length; i < l; ++i ) {
    if( headers[i].name == 'User-Agent' ) {
      headers[i].value = '>>> Your new user agent string here <<<';
      console.log(headers[i].value);
      break;
    }
    // If you want to modify other headers, this is the place to
    // do it. Either remove the 'break;' statement and add in more
    // conditionals or use a 'switch' statement on 'headers[i].name'
  }

  blockingResponse.requestHeaders = headers;
  return blockingResponse;
},
{urls: [ "<all_urls>" ]},['requestHeaders','blocking']);
于 2013-03-19T18:22:46.703 に答える
10

ここの拡張機能でこれを修正しまし た: https://github.com/devinrhode2/tweet-bar私にとってはそれほど重要ではありません。chrome.webRequest.onBeforeSendHeaders.addListenerwebRequest, webRequestBlocking

重要事項:

  • manifest.json "background": { "persistent": true,
  • "permissions": [ "webRequest", "webRequestBlocking",

manifest.json でこれらの変更を行った場合、実際には、変更が反映されていることを確認するためだけに拡張機能を再インストールすることを検討する必要があります。

これは私のフィルターコードです。あなたのものは同一であってはなりません。ここのドキュメントを参照してください https://developer.chrome.com/extensions/webRequest

chrome.webRequest.onBeforeSendHeaders.addListener((req) => {
  console.log('onBeforeSendHeaders');
  req.requestHeaders.forEach(function(header, index){
    console.log(header.name+':', header.value);
    if (headers[header.name.toLowerCase()]) {
      console.log('set header:'+header.name, 'to:'+headers[header.name.toLowerCase()]);
      req.requestHeaders[index].value = headers[header.name.toLowerCase()]
    }
  })
  return {requestHeaders: req.requestHeaders};
},{
  urls: ['https://twitter.com/i/tweet/create'],
  types: ["xmlhttprequest"]
},[
  'blocking',
  'requestHeaders'
]);

また、これらのヘッダーを xhr リクエストに追加しましたが、問題はなく、通常のサイトと同じように表示されます。

  //add headers:
  var headers = {
    'content-type': 'application/x-www-form-urlencoded',
    accept: 'application/json, text/javascript, */*; q=0.01',
    origin: 'https://twitter.com',
    referer: 'https://twitter.com/',
    'x-requested-with': 'XMLHttpRequest'
  };
  console.log('change')
  Object.keys(headers).forEach((header) => {
    postXhr.setRequestHeader(header, headers[header]);
  })
于 2016-06-22T22:00:28.227 に答える
0

これがマニフェスト構成です

"permissions": [ 
    "webRequestBlocking"
    ,"webRequest"
    ,"http://*.beibei.com/*"
],
"background" : {
    "page"       : "xxx.html",
    "persistent" : true
}

これがJavaScriptのデモコードです

$( function() {
    // add event listners
    chrome.webRequest.onBeforeRequest.addListener(
        function(details) { 
            console.log('onBeforeRequest', details);
        },
        {urls: ["http://www.beibei.com/"]},
        []
    );

    chrome.webRequest.onBeforeSendHeaders.addListener(
        function(details) {
            console.log('onBeforeSendHeaders', details);
        },
        {urls: ["http://www.beibei.com/"]},
        ["requestHeaders"]
    );

    chrome.webRequest.onCompleted.addListener( 
        function(details) {
            console.log('onCompleted', details);
        },
        {urls: ["http://www.beibei.com/"]},
        []
    );

    // do a GET request, so that relative events will be fired, need jquery here
    $.get('http://www.beibei.com/');
});
于 2016-12-17T07:18:19.980 に答える