Can I modify outgoing request headers with a Chrome Extension?

Viewed 125841

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 Answers

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

You could install ModHeader extension and add headers:

enter image description here

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/

Related