简体   繁体   中英

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.

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);
  })
}

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 )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM