1

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
  • 3
    Your code is incorrect in MV2 as it lacks 'blocking' in the last array, however it won't work in MV3 anyway as this mode is not supported there. Commented Sep 16, 2022 at 9:55

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Please mark your answer as "accepted" (the OP can mark any answer as "accepted", even if he's the one who wrote it)
@ThomasMueller I appreciate the tip though SO gives me a notification saying I can only accept my own answer 2 days after I have posted it.
however declarativeNetRequest does not allow changing the UA header in mV3. Frustratingly there doesnt seem to be any way to change UserAgent with an extension using MV3

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.