'Using fetch in chrome extension sends null origin header

When sending cross origin requests using the fetch API the origin request header is being set to null instead of the chrome://xxxxx that I was expecting. Using fetch in both the background.js context as well as the injected iframe context result in the same behavior.

When I use XMLHttpRequest instead it sends the expected origin header.

Is there some control in the manifest.json (or something else) that is preventing fetch from behaving as expected? My understanding is that the origin header is "protected", so trying to set it manually obviously doesn't work.



Solution 1:[1]

I noticed the same issue. My workaround is to use XMLHttpRequest instead of fetch like what OP mentioned. With XHR, it does send origin as chrome://**extension-id** but not referer header. No referer header with fetch too.

In case somebody wonders how to use XMLHttpRequest. The following code snippet taken from MDN XMLHttpRequest readState document:

var xhr = new XMLHttpRequest();
console.log('UNSENT', xhr.readyState); // readyState will be 0

xhr.open('GET', '/api', true);
console.log('OPENED', xhr.readyState); // readyState will be 1

xhr.onprogress = function () {
    console.log('LOADING', xhr.readyState); // readyState will be 3
};

xhr.onload = function () {
    console.log('DONE', xhr.readyState); // readyState will be 4
};

xhr.send(null);

If you prefer to use a promise, you can use a promise to wrap XMLHttpRequest. You can check out this article on how to turn XMLHttpRequest into promise for more information.

function xhr(params) {
  return new Promise(function(resolve, reject) {
    let xhr = new XMLHttpRequest();
    let url = '';

    xhr.open('POST', url + params);

    xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    xhr.responseType = '';

    xhr.onerror = function() {
      reject(new Error('error'));
    };

    xhr.onload = function() {
      // do something with response
      let res = xhr.response;
      resolve(res);
    };

    // send request
    body = JSON.stringify({ params });
    xhr.send(body);
  })
}

Solution 2:[2]

There should be some way to make fetch send the Origin header when executed from the extension background worker (with manifest V3)... What about using specific referrerPolicy? (https://googlechrome.github.io/samples/fetch-api/fetch-referrer-policy.html)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 AlexV