How to add Origin header in content-script ajax call

Hi,
Recently I am making a very simple ajax post request in content-script, for example

Blockquote
var xhr = new XMLHttpRequest();
xhr.open(‘POST’, tokenUrl, true);
xhr.setRequestHeader(‘Content-Type’, ‘application/x-www-form-urlencoded’);
xhr.onreadystatechange = function() {
if (this.readyState === XMLHttpRequest.DONE && this.status === 200) {
console.log(‘Success’);
}
}
xhr.send(‘a=1&b=2’);

please note that the tokenUrl is actually on the same domain as the current tab’s domain, so actually I am not doing any CORS.
However if I inspect the network, the Origin header is not set, I also tried on Chrome extension, the Origin header is set correctly.

Besides, if I directly use the same ajax on Firefox tab’s console, the Origin header is set correctly

So it seems Firefox content-script misses the Origin header, Is there any idea to add it?

Thank you very much

Hi,

Did you try doing your request with fetch API instead? Fetch should automatically fill the origin header on both Firefox and Chrome.

1 Like

From version 58 onwards, extensions that need to perform requests that behave as if they were sent by the content itself can use content.XMLHttpRequest and content.fetch() instead.

1 Like

Thanks sylvaing, I tried fetch, works perfect.
Now I am thinking I should also use fetch in Chrome:)

Thanks freaktechnik for the documentation, it seems Mozilla remove Origin and Referrer header on purpose.

unfortunately I can’t set the cross-domain access in manifest permission, and I do prefer the Origin and Referrer added because my server side has quite some strict validation

the content.fetch works perfectly for now, but I am a bit concerned that if Mozilla will remove those header in content.fetch in the future.

content.fetch behaves exactly like the fetch of the website’s context, so it should never lose the origin header.

1 Like