javascript chrome.webRequest 不起作用?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15502691/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 01:00:34  来源:igfitidea点击:

chrome.webRequest not working?

javascriptgoogle-chromegoogle-chrome-extension

提问by user1326293

I'm trying to implement the chrome.webRequest API in my extension but for some reason it's just not working no matter what I do. Can someone post an example of usage? or correct my mistakes? Basically what I'm trying to do is to intercept the recieved headers from a response.

我正在尝试在我的扩展程序中实现 chrome.webRequest API,但由于某种原因,无论我做什么它都不起作用。有人可以发布使用示例吗?或纠正我的错误?基本上我想做的是拦截从响应中收到的标头。

This is an implementation for onBeforeSendHeaders but I'd like to use OnHeadersRecieved as well :

这是 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 );

this is my manifest file:

这是我的清单文件:

    {
   "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”, “<all_urls>”],
   "update_url": "***/Chrome/UpdateVersion.xml",
   "version": "1.3"
}

the error I get from Chrome is: Uncaught TypeError: Cannot read property 'onBeforeSendHeaders' of undefined

我从 Chrome 得到的错误是: Uncaught TypeError: Cannot read property 'onBeforeSendHeaders' of undefined

Anyone see anything wrong??? thanks

有人看到有什么不对吗???谢谢

回答by BeardFist

Well for an example of usage I can give you this working code. I wrote it this way because the other way seems backwards to me but that is just my personal preference, they should both work the same.

好吧,作为使用示例,我可以为您提供此工作代码。我这样写是因为另一种方式在我看来是倒退的,但这只是我个人的喜好,它们应该都一样。

Manifest

显现

{
  "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

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']);

回答by Devin G Rhode

I just fixed this in my extension here: https://github.com/devinrhode2/tweet-barWhat I needed to do was use chrome.webRequest.onBeforeSendHeaders.addListener, but that also meant adding in the webRequest, webRequestBlockingpermissions.. would be better to use declarativeWebRequest, but this project isn't that important to me.

我只是在我的扩展中修复了这个:https: //github.com/devinrhode2/tweet-bar我需要做的是使用chrome.webRequest.onBeforeSendHeaders.addListener,但这也意味着添加webRequest, webRequestBlocking权限..使用 declarativeWebRequest 会更好,但是这个项目对我来说不是那么重要。

Key things:

关键事项:

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

When you make these changes in the manifest.json, you should actually consider re-installing the extension just to make sure the change is being picked up.

当您在 manifest.json 中进行这些更改时,您实际上应该考虑重新安装扩展程序,以确保更改被选中。

This is my filter code. Yours should not be identical. See the docs here https://developer.chrome.com/extensions/webRequest

这是我的过滤器代码。你的不应该是相同的。请参阅此处的文档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'
]);

I also added these headers to my xhr request, which doesn't hurt, makes you appear more similar to the normal site:

我还将这些标头添加到我的 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]);
  })

回答by lyfing

Here is the manifest config

这是清单配置

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

Here is the javascript demo code

这是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/');
});