chrome.webRequest not working?

后端 未结 4 1022
滥情空心
滥情空心 2020-12-24 07:31

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 c

相关标签:
4条回答
  • 2020-12-24 07:49

    Add the required permissions for the extension in manifest.json, you might not need webRequestBlocking depending on what u want to do.

    ...
    "permissions": [
        "<all_urls>","webRequest","webRequestBlocking" 
      ],"background": {
        "scripts": ["background.js"],
        "persistent": true
    }
    ...
    

    After adding the required permissions for your extension in the manifest.json file, make sure you click on the update button and if that does not work or the browser does not have an update button then reinstall the extension.

    0 讨论(0)
  • 2020-12-24 08:02

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

    Key things:

    • 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.

    This is my filter code. Yours should not be identical. See the docs here 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:

      //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]);
      })
    
    0 讨论(0)
  • 2020-12-24 08:09

    Here is the manifest config

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

    Here is the javascript demo code

    $( 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/');
    });
    
    0 讨论(0)
  • 2020-12-24 08:10

    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

    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']);
    
    0 讨论(0)
提交回复
热议问题