0

I tried the following code (code is from here) which can change the value of navigator.userAgent in browsers, and it works fine! after running this code, when I check the value of navigator.userAgent, it is changed to the new value. but then when I send a post request with ajax, the user-agent header which is automatically sent with my request, has not changed and is the actual user agent of the browser. why the user agent has not changed for ajax request?

function setUserAgent(window, userAgent) {
// Works on Firefox, Chrome, Opera and IE9+
if (navigator.__defineGetter__) {
    navigator.__defineGetter__('userAgent', function () {
        return userAgent;
    });
} else if (Object.defineProperty) {
    Object.defineProperty(navigator, 'userAgent', {
        get: function () {
            return userAgent;
        }
    });
}
// Works on Safari
if (window.navigator.userAgent !== userAgent) {
    var userAgentProp = {
        get: function () {
            return userAgent;
        }
    };
    try {
        Object.defineProperty(window.navigator, 'userAgent', userAgentProp);
    } catch (e) {
        window.navigator = Object.create(navigator, {
            userAgent: userAgentProp
        });
    }
}
}
Soheil
  • 587
  • 4
  • 20
  • Does this answer your question? [JQuery Ajax Request: Change User-Agent](https://stackoverflow.com/questions/5771878/jquery-ajax-request-change-user-agent) – Ivar Nov 25 '20 at 12:47
  • 1
    What makes you think that AJAX requests use `window.navigator` as its source? As of 2015 it is no longer a forbidden header, which means that you _should_ be able to set it using [`setRequestHeader()`](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/setRequestHeader), but Chrome still [silently drops it](https://developer.mozilla.org/en-US/docs/Glossary/Forbidden_header_name). – Ivar Nov 25 '20 at 12:57
  • @Ivar thanks for your explanation. setting custom user-agent header does not work in any browser. tested on chrome (as you said), safari and edge – Soheil Nov 25 '20 at 13:45
  • @Ivar so there is no practical way to change the ajax user agent header?! – Soheil Nov 25 '20 at 13:47
  • 1
    Definitely not for Chrome. The same seems to apply for Edge (Edge is also based on Chromium). It does seem to work in Firefox. – Ivar Nov 25 '20 at 13:55

0 Answers0