Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Firefox fetch API: How to omit the "origin" header in the request?

If you make a fetch request in a Firefox WebExtension, it will automatically set the "origin" header. For example, when I run this code inside a WebExtensions ...

fetch('http://example.com/')

... the resulting request contains the header: "origin: moz-extension://539a0d5b-60d9-4726-b3de-27d6979edc26"

Running the same code in Chromium will not set the header. (Update: This is not always true, as Chrome may also add the header: "origin: chrome-extension://...".)

Is there an option to send the request without "origin"?


I did not find an option in the fetch API. So, far the only solution that I see is to remove the header using the webRequest API, but that seems overly complicated.

like image 618
Philipp Claßen Avatar asked Nov 17 '17 17:11

Philipp Claßen


1 Answers

Both Firefox and Chrome automatically fill the origin header when a WebExtension sends a requests using the fetch API. There is currently no API option to prevent it.

If you do not want that behavior, you have two options:

  1. Use the old XMLHttpRequest API instead of fetch
  2. Manually strip the origin header using the webRequest API

Option 1 will work, as the origin header is only set by the fetch API. For option 2, you will have to install an onBeforeSendHeaders handler to remove the header before the request leaves the browser:

function originWithId(header) {
  return header.name.toLowerCase() === 'origin' &&
         (header.value.indexOf('moz-extension://') === 0 ||
          header.value.indexOf('chrome-extension://') === 0);
}

chrome.webRequest.onBeforeSendHeaders.addListener(
  (details) => {
    return {
      requestHeaders: details.requestHeaders.filter(x => !originWithId(x))
    }
  },
  {urls: ["<all_urls>"]},
  ["blocking", "requestHeaders"]
);

To use the API, you will need to add "webRequest" and "webRequestBlocking" to the permissions in manifest.json.

like image 139
Philipp Claßen Avatar answered Sep 18 '22 02:09

Philipp Claßen