Setting a custom userAgent in HTML or JavaScript

前端 未结 4 1454
野趣味
野趣味 2020-12-17 10:03

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

4条回答
  •  南笙
    南笙 (楼主)
    2020-12-17 11:04

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

提交回复
热议问题