66

I can't see an answer to this in the Developer's Guide, though maybe I'm not looking in the right place.

I want to intercept HTTP requests with a Chrome Extension, and then forward it on, potentially with new/different HTTP headers - how can I do that?

Peter Boughton
  • 110,170
  • 32
  • 120
  • 176
  • This is as close as I can find: http://code.google.com/chrome/extensions/content_scripts.html – Romain Hippeau Jul 18 '10 at 04:13
  • Consider changing the accepted answer. The current accepted answer has become obsolete. The [newer answer](http://stackoverflow.com/questions/3274144/can-i-modify-outgoing-request-headers-with-a-chrome-extension/9143714#9143714) is correct. – Rob W Mar 24 '14 at 23:11
  • If/when that answer is updated with an actual explanation and example of how to do it, I'll go ahead and mark it as the solution. A link alone is not an answer. – Peter Boughton Mar 24 '14 at 23:28
  • @PeterBoughton That just happened. – Xan Jan 14 '15 at 08:09
  • Also related: http://stackoverflow.com/a/29832996/748858 – mgilson Mar 08 '17 at 17:04
  • @mgilson It's not related. The link that you gave lets you copy the request as cURL and modify the headers manually and then send the request. OP wanted to do it right inside chrome with a chrome extension. – Sachin Jain Jan 17 '23 at 12:17

7 Answers7

75

PS: I am the author of Requestly - Chrome/Firefox extension to modify HTTP requests & responses.

It was certainly not possible when OP asked the question but now you can use WebRequest API with Manifest V2 and DeclarativeNetRequest API with Manifest V3 to write your own extension to modify Request & Response Headers.

Manifest V2 code

chrome.webRequest.onBeforeSendHeaders.addListener(
  function(details) {
    for (var i = 0; i < details.requestHeaders.length; ++i) {
      if (details.requestHeaders[i].name === 'User-Agent') {
        details.requestHeaders.splice(i, 1);
        break;
      }
    }
    return { requestHeaders: details.requestHeaders };
  },
  {urls: ['<all_urls>']},
  ['blocking', 'requestHeaders' /* , 'extraHeaders' */]
  // uncomment 'extraHeaders' above in case of special headers since Chrome 72
  // see https://developer.chrome.com/extensions/webRequest#life_cycle_footnote
);

Google Chrome is deprecating webRequest Blocking APIs in the Manifest V3. As per the official statement from Google on 28th Sep 2022, all extensions with Manifest v2 won't run on Chrome from June 2023 onwards. Here's an approach to Modify Request & Response headers with Manifest v3 - https://github.com/requestly/modify-headers-manifest-v3

Manifest V3 Code:

rules.ts

const allResourceTypes = 
    Object.values(chrome.declarativeNetRequest.ResourceType);

export default [
  {
    id: 1,
    priority: 1,
    action: {
      type: chrome.declarativeNetRequest.RuleActionType.MODIFY_HEADERS,
      requestHeaders: [
        {
          operation: chrome.declarativeNetRequest.HeaderOperation.SET,
          header: 'x-test-request-header',
          value: 'test-value',
        },
      ]
    },
    condition: {
      urlFilter: '/returnHeaders',
      resourceTypes: allResourceTypes,
    }
  },
  {
    id: 2,
    priority: 1,
    action: {
      type: chrome.declarativeNetRequest.RuleActionType.MODIFY_HEADERS,
      responseHeaders: [
        {
          operation: chrome.declarativeNetRequest.HeaderOperation.SET,
          header: 'x-test-response-header',
          value: 'test-value',
        },
      ]
    },
    condition: {
      urlFilter: 'https://testheaders.com/exampleAPI',
      resourceTypes: allResourceTypes,
    }
  },
];

background.ts

import rules from './rules';

chrome.declarativeNetRequest.updateDynamicRules({
  removeRuleIds: rules.map((rule) => rule.id), // remove existing rules
  addRules: rules
});

The complete source code is available in the GitHub repo - https://github.com/requestly/modify-headers-manifest-v3

If you want to use an existing Chrome/Firefox/Edge Extension, you can use Requestly which allows you to modify request and response headers. Have a look at this snapshot:

Headers Rule Screenshot

Sachin Jain
  • 21,353
  • 33
  • 103
  • 168
  • 12
    I would tone down the **`ADVERTISEMENT`**. 1) You should explicitly disclose it's your own creation, 2) Maybe a huge screenshot is out of place. – Xan Jan 14 '15 at 08:11
  • 7
    @Xan I have added PPS saying "I am the author". You are right I should have done this in first place. Snapshot may/may not be out of place, I am going to be it here. If you strongly feel it should not be there, remove it. I am just fine with it. Thanks for your input. I appreciate – Sachin Jain Jan 14 '15 at 08:49
  • 49
    Thanks blunderboy, and don't worry - your image is perfectly fine. You being the author was already self-evident from the repository link, and given that you first identified the API and showed example code (not to mention that it's an open source project), fussing over it being an "advertisement" is a pretty dumb thing to do. – Peter Boughton Mar 02 '15 at 22:50
  • 4
    Well I am happy - with Requestly I did my small test in 2 minutes which would have taken >20 minutes coding with the API. – Fletch Jul 13 '16 at 13:44
  • 2
    +1 - Using it to debug ajax, setting to Modify Headers -> Add -> Request -> "X-Requested-With" -> "XMLHttpRequest" – Theraot Aug 31 '16 at 04:10
  • @sachinjain024 I tried to use above code but it doesn't work for preflighted OPTIONS requests. Is there any way to make it work with OPTIONS request? – BiJ Dec 10 '16 at 22:42
  • @BiJ From Chrome docs - `Use the chrome.webRequest API to observe and analyze traffic and to intercept, block, or modify requests in-flight.`. OPTIONS request is a preflight request and thus Chrome does not allow modification to it. – Sachin Jain Dec 11 '16 at 23:49
  • 1
    Um... this add-in doesn't actually work -- the sites can't see the headers you add, and if you look in the network console, you can see that the request headers were never added. – BrainSlugs83 Apr 06 '17 at 22:51
  • @BrainSlugs83 There is a chrome bug due to which you will not be able to see the modifications in response headers. Moreover, you need to check if your Url match pattern is actually right now. open an issue on github.com/requestly/requestly-issues and I will look further into it. – Sachin Jain Apr 07 '17 at 03:12
  • I am able to do redirect/cancel requests etc with requestly but now add/delete/modify headers. Do I need to change settings as well to do it in chrome – Vikram3891 May 03 '18 at 12:26
  • @Vikram3891If you are modifying response headers, headers will be m odified by the extension but modifications are not visible in dev tool. This is a chrome bug. There is a list of headers which chrome does not allow you to modify. Please check this https://medium.com/@requestly_ext/list-of-headers-not-allowed-to-be-modified-by-chrome-extensions-c850b5c02fff. Reachout on requestly.extension@gmail.com for any issues – Sachin Jain May 04 '18 at 09:37
  • @sachinjain024 Yep. It seems so. had to use Firefox finally. Thanks for reply. – Vikram3891 May 06 '18 at 06:53
  • 1
    Where has this been all of my life? Here's the link to Chrome & Firefox extension: http://www.requestly.in/ – P. T. Mar 26 '19 at 15:39
  • Look at the post below from @jossef-harush-kadouri for how to modify custom request headers using manifest version 3. – Kaushik Sep 29 '22 at 14:38
12

Modifying request headers ( https://developer.chrome.com/extensions/webRequest ) is supported in chrome 17.

Idris Mokhtarzada
  • 1,034
  • 12
  • 21
4

Keep in mind that starting from chrome 72, some headers are not allowed unless you add extraHeaders in opt_extraInfoSpec So the above example in @sachinjain024's answer will look something like this:

chrome.webRequest.onBeforeSendHeaders.addListener(
  function(details) {
    for (var i = 0; i < details.requestHeaders.length; ++i) {
      if (details.requestHeaders[i].name === 'User-Agent') {
        details.requestHeaders.splice(i, 1);
        break;
      }
    }
    return { requestHeaders: details.requestHeaders };
  },
  {urls: ['<all_urls>']},
  [ 'blocking', 'requestHeaders', 'extraHeaders']
);

For more info, check the documentation Screenshot from the documentation https://developer.chrome.com/extensions/webRequest#life_cycle_footnote

Mahmoud Felfel
  • 3,051
  • 3
  • 26
  • 19
3

You are looking at the right place, but intercepting HTTP requests does not exist yet, but the extension team is aware that it's a popular request and would like to get to it sometime in the near future.

Mohamed Mansour
  • 39,445
  • 10
  • 116
  • 90
3

For extensions using manifest version 3, you can no longer use chrome.webRequest.onBeforeSendHeaders.*. The alternative is chrome.declarativeNetRequest

Make the following changes in your manifest.json:

{
  ...
  "manifest_version": 3,
  "background": {
    "service_worker": "background.js"
  },
  "host_permissions": ["<all_urls>"],
  "permissions": [
    "declarativeNetRequest"
  ],
  ...
}
  • "<all_urls>" is for modifying all outgoing urls's headers. Restrict this for your scope of your work

Make the following changes in your background.js:

// ...

const MY_CUSTOM_RULE_ID = 1

chrome.declarativeNetRequest.updateDynamicRules({
    removeRuleIds: [MY_CUSTOM_RULE_ID],
    addRules: [
        {
            id: MY_CUSTOM_RULE_ID,
            priority: 1,
            action: {
                type: "modifyHeaders",
                requestHeaders: [
                    {
                        operation: "set",
                        header: "my-custom-header",
                        value: "my custom header value"
                    }
                ]
            },
            condition: {
                "resourceTypes": ["main_frame", "sub_frame"]
            },
        }
    ],
});

Result

enter image description here

Read the docs https://developer.chrome.com/docs/extensions/reference/declarativeNetRequest/

Jossef Harush Kadouri
  • 32,361
  • 10
  • 130
  • 129
  • Just came across this while looking to add an update using manifest V3 myself. Added an upvote to this. Thanks, Jossef! – Kaushik Sep 29 '22 at 14:36
2

You could install ModHeader extension and add headers:

enter image description here

Taras Melnyk
  • 3,057
  • 3
  • 38
  • 34
1

You can use WebRequest API which is now deprecated it allows you to modify request/response headers. You can upgrade your extension to Manifest V3 to be able to use DeclativeNetRequest which also supports modifying request/response headers.

Or you can install Inssman chrome extension. It allows you to modify HTTP(S) request/response headers, reqirect and block request, return custom data like HTML/CSS/JS/JSON and more.   And it is open source project

Inssman

enter image description here

MegaWm
  • 11
  • 2