Changing User-Agent in XMLHttpRequest from Chrome Extension

I am trying to send an HTTP request from an extension in which I need to change the User-Agent.

My code is as follows:

function getXMLHttpRequest(method, url, extraHeaders) { var xhr = new XMLHttpRequest(); xhr.open(method, url, true) for (var headerKey in extraHeaders) { xhr.setRequestHeader(headerKey, extraHeaders[headerKey]); } return xhr; } //.... getXMLHttpRequest("POST", "....", { "User-Agent": "Blahblahblah" }) 

Then I get the error "Installation of unsafe header refused: UserAgent"

I need to change this because my Backend must have a special User-Agent, is it possible to do this from the extension?

I tried the webRequest API to change the header before sending the request, but it says that it does not work with XMLHttpRequest made from extensions to prevent blocking.

+6
source share
1 answer

You can easily change the User-Agent header using the webRequest API.
For a code example, see Associate a user user agent with a specific Google Chrome page / tab .

Take the code from this answer and change "main_frame", "sub_frame" to "xmlhttprequest" to change the network requests initiated with XMLHttpRequest .

Obviously, to prevent deadlocks, this method does not work with synchronous requests (i.e., when the third parameter xhr.open set to false ).

+4
source

All Articles