Setting a custom userAgent in HTML or JavaScript

烂漫一生 提交于 2020-01-10 03:45:25

问题


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.


回答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




回答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);
    });
});



回答3:


If you are using a XMLHttpRequest you can set a custom Request Header like:

var xhr = new XMLHttpRequest(...);
xhr.setRequestHeader("User-Agent","test");



回答4:


You will never change a user Agent in HTML, html is the message not messenger.

Indeed you can do it with a javascript code, but it's dangerous if you ever deploy it in production.

It's far safer to use an agent switcher:

https://addons.mozilla.org/fr/firefox/addon/user-agent-switcher/

https://chrome.google.com/webstore/detail/user-agent-switcher-for-c/djflhoibgkdhkhhcedjiklpkjnoahfmg



来源:https://stackoverflow.com/questions/23248525/setting-a-custom-useragent-in-html-or-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!