Changing User-Agent in XMLHttpRequest from a Chrome extension
google-chrome-extension
Solution
You can easily change the User-Agent header with the `webRequest` API. For sample code, see Associate a custom user agent to a specific Google Chrome page/tab.
Take the code from that answer, and change `"main_frame", "sub_frame"` to `"xmlhttprequest"` to modify network requests initiated via `XMLHttpRequest`.
Obviously, to prevent deadlocks, this method does not work with synchronous requests ( i.e. when the third parameter of `xhr.open` is set to `false`).
Problem
I'm trying to send a HTTP request from a Extension in which I need to change the User-Agent. My code looks like this: ``` 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 an error "Refused to set unsafe header: UserAgent" I need to change that because my Backend needs to have an special User-Agent, is it possible to do that from an extension? I tried webRequest API, to change the header before sending the request, but it says it does not work with XMLHttpRequest made from extensions in order to prevent locking.