Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing User-Agent in XMLHttpRequest from a Chrome extension

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.

like image 476
HyLian Avatar asked Jan 13 '14 11:01

HyLian


People also ask

How do I change the User-Agent in Chrome extension?

User-Agent Switcher is a quick and easy way to switch between user-agents. Just right click on any page and select your user-agent. This Chrome extension adds a toolbar button and a menu to switch between user-agents. Browse with our predefined user-agents or add your own user-agents.

How do I enable XMLHttpRequest in Chrome?

1. Open Chrome browser 2. Go to chrome://flags/#allow-sync-xhr-in-page-dismissal 3. Change the drop-down selection from “Default” or “Disabled” to “Enabled”.

Where is the User-Agent string in Chrome?

Google Chrome Chrome's user agent switcher is part of its Developer Tools. Open them by clicking the menu button and selecting More Tools > Developer Tools. You can also use press Ctrl+Shift+I on your keyboard.

What does reduce User-Agent request header do?

# What is User-Agent reduction? User-Agent (UA) reduction is the effort to minimize the identifying information shared in the User-Agent string which may be used for passive fingerprinting. As these changes are rolled out, all resource requests will have a reduced User-Agent header.


1 Answers

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).

like image 120
Rob W Avatar answered Sep 20 '22 16:09

Rob W