76

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?

6

8 Answers 8

84

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

18
  • 13
    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
    Commented Jan 14, 2015 at 8:11
  • 9
    @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 Commented Jan 14, 2015 at 8:49
  • 56
    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. Commented Mar 2, 2015 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
    Commented Jul 13, 2016 at 13:44
  • 3
    +1 - Using it to debug ajax, setting to Modify Headers -> Add -> Request -> "X-Requested-With" -> "XMLHttpRequest"
    – Theraot
    Commented Aug 31, 2016 at 4:10
12

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

7

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/

1
  • Just came across this while looking to add an update using manifest V3 myself. Added an upvote to this. Thanks, Jossef!
    – Kaushik
    Commented Sep 29, 2022 at 14:36
4

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.

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

2

You could install ModHeader extension and add headers:

enter image description here

5
  • 1
    how to remove header using this extension?
    – ssi-anik
    Commented May 26, 2021 at 8:26
  • 1
    You can remove the headers that was added by you only. Commented May 26, 2021 at 12:06
  • 2
    9/28/2023 warning: this extension will add google ads on webpage. Commented Sep 28, 2023 at 7:04
  • Yes, you can totally do that and then ModHeader is sneakingly injecting ads all over your google search result pages. Not cool. Commented Oct 3, 2023 at 16:34
  • 3
    this one now injects advertisements at Google search result page.
    – Arun CM
    Commented Oct 4, 2023 at 6:32
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

0

I just tried Chrome, FireFox and Edge.

Without installing any extension, only Edge allows me to replace the header "referer" and resend.

Not the answer you're looking for? Browse other questions tagged or ask your own question.