3

I'm writing a Chrome extension in pure JavaScript and wish to change the user agent for HTTP requests to a given URL as the owner of that URL has requested that a user agent of a certain format be used.

The following code works until the user agent modification line is added, at which point the Chrome inspector console give the error Refused to set unsafe header "User-Agent".

var xhr = new XMLHttpRequest();
xhr.open("GET", serviceURL, true, username, password);
xhr.setRequestHeader('User-Agent', 'MyExtensionName/0.0.1');
xhr.onreadystatechange = function() {
    // do some stuff
}
xhr.send(null);

Why is it not possible to modify the user agent in this manner?

101
  • 8,514
  • 6
  • 43
  • 69

1 Answers1

7

You cannot set that heading in a request of that kind, the browser will block it - along with many other header types.

In a Chrome extension however you can use chrome.webRequest to alter headers.

This will adjust a User Agent. Change to your desired URL, following the Match Patterns guidelines. Remember to add permissions for webRequest and webRequestBlocking to your manifest.

chrome.webRequest.onBeforeSendHeaders.addListener(function(details){
    for(var i=0; i < details.requestHeaders.length; ++i){
        if(details.requestHeaders[i].name === "User-Agent"){
            details.requestHeaders[i].value = "Desired User Agent Here";

            break;
        }
    }
    return {requestHeaders: details.requestHeaders};
}, {urls: ["<all_urls>"]}, ["blocking", "requestHeaders"]);
Alex
  • 191
  • 4