Why isn't the User Agent being modified using the Chrome API?

Viewed 30

Using the Google Chrome Extensions API, I am attempting to modify the User-Agent header that is sent with HTTP requests with the following code:

chrome.webRequest.onBeforeSendHeaders.addListener((details) => {
    let reqHeaders = details.requestHeaders;
    if (reqHeaders) {
        reqHeaders.forEach((header) => {
            if (header.name == "User-Agent") {
                header.value = "Mozilla/5.0 (X11; CrOS x86_64 8172.45.0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.64 Safari/537.36"
                console.log(header.value) //Extension does change the value but it is never applied
            }
        });
    }
    return {requestHeaders: reqHeaders}; //This should apply the new value but doesn't
}, {urls: ["<all_urls>"]}, ["requestHeaders"]);

My User-Agent according to the Chrome Network Monitor: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/105.0.0.0 Safari/537.36

I have read over the documentation numerous times and have been unable to find a wrongdoing in my code. Is there anything I am missing?

1 Answers

To any future users who have stumbled upon this problem, I have found a solution. The webRequest API callbacks are only supported when the extension is added to the ExtensionInstallForcelist. The API isn't deprecated (yet) which is why I originally thought my code would work. You are now being encouraged to use the declarativeNetRequest API as a replacement.

The webRequest API gives you more control over how you process request information programatically, but the declarativeNetRequest has a higher priority, less security restrictions, and less memory usage.

Related