Banks
Banks

Reputation: 1

How to change the user agent of Chrome using javascript?

I know there are one or two posts out there concerning a similar question but the answers never helped me or it just didn't work. I wanted to create a chrome extension that has changing a user agent being a part of it (I know there are user-agent changer extensions out there but that's not what I'm trying to make). Thanks

Upvotes: 0

Views: 5251

Answers (1)

Xan
Xan

Reputation: 77531

You will need the webRequest API.

User agent can be changed in the onBeforeSendHeaders event. In fact, the documentation has a very pertinent example in it.

  chrome.webRequest.onBeforeSendHeaders.addListener(
    function(details) {
      for (var i = 0; i < details.requestHeaders.length; ++i) {
        if (details.requestHeaders[i].name === 'User-Agent') {
          /* change details.requestHeaders[i].value here */
          break;
        }
      }
      return {requestHeaders: details.requestHeaders};
    },
    {urls: ["<all_urls>"]},
    ["blocking", "requestHeaders"]);

Upvotes: 4

Related Questions