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

1

9

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.

Enlarge answered 17/11, 2017 at 17:39 Comment(0)
E
6

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.

Enlarge answered 28/3, 2018 at 16:44 Comment(4)
It seems that Firefox now adds the origin header to XMLHttpRequests no matter what, and this no longer works...Observatory
@WilsonBiggs I tried on Firefox 69.0.1 and could not reproduce that XMLHttpRequest now sets the origin header. But I triggered the requests from the debug console while attached to an extension. I still got the origin header with fetch, though. Are you on a newer Firefox version, or is there another twist to reproduce? In any case, it would be sad if option 1 would stop working, as not all extensions have permission to use the webRequest API. That API gives a lot of power and adding it only for that purpose is hard to justify.Eulaeulachon
I think the issue was with something else, as after a rewrite of what I was working on this wasn't happening anymore. Sorry for the false alarm.Observatory
Chrome now adds the Origin header with XMLHttpRequests too :/Sabrasabre

© 2022 - 2024 — McMap. All rights reserved.