'Setting a custom userAgent in HTML or JavaScript
Is there any way to do this? I'm trying to send a GET request to a website, but I want to customize my UserAgent. Is there any way to do this in pure HTML and JavaScript? I'd like it to all execute locally.
Solution 1:[1]
This is working for me.
Object.defineProperty(navigator, 'userAgent', {
get: function () { return 'Mozilla/5.0 (Windows NT 6.2; WOW64; rv:28.0) Gecko/20100101 Firefox/28.0)'; }
});
It is an updated version of code4coffee's answer as Object.prototype.__defineGetter__() is deprecated: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/__defineGetter__
Solution 2:[2]
You can programmatically do this in Javascript (this example mocks up Firefox):
navigator.__defineGetter__('userAgent', function () {
return "Mozilla/5.0 (Windows NT 6.2; WOW64; rv:28.0) Gecko/20100101 Firefox/28.0)"
});
navigator.__defineGetter__('appName', function () {
return "Netscape"
});
You can then view the changes in the console via (and of course check these via Javascript):
navigator.userAgent
navigator.appName
Here's an example of a test that should work (using Jasmine):
describe("isUserAgentInternetExplorer", function () {
it("should return false for Firefox", function () {
navigator.__defineGetter__('userAgent', function () {
return "Mozilla/5.0 (Windows NT 6.2; WOW64; rv:28.0) Gecko/20100101 Firefox/28.0)"
});
navigator.__defineGetter__('appName', function () {
return "Netscape"
});
//your code here...
expect(...your code here...).toEqual(false);
});
});
Solution 3:[3]
2022
You are not allowed to modify the following headers, according to Fetch WHATWG spec.
And in 2022 all the evergreen browsers have implemented this requirement.
`Accept-Charset`
`Accept-Encoding`
`Access-Control-Request-Headers`
`Access-Control-Request-Method`
`Connection`
`Content-Length`
`Cookie`
`Cookie2`
`Date`
`DNT`
`Expect`
`Host`
`Keep-Alive`
`Origin`
`Referer`
`TE`
`Trailer`
`Transfer-Encoding`
`Upgrade`
`Via`
As well as headers, starting with proxy- or sec-.
These are forbidden so the user agent remains in full control over them.
Solution 4:[4]
If you are using a XMLHttpRequest you can set a custom Request Header like:
var xhr = new XMLHttpRequest(...);
xhr.setRequestHeader("User-Agent","test");
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | c24w |
| Solution 2 | |
| Solution 3 | avalanche1 |
| Solution 4 | SeDav |
