How to target Edge browser with javascript

后端 未结 9 733
無奈伤痛
無奈伤痛 2020-12-05 09:26

I know you should do feature detection where possible, but can you detect in Javascript if the browser is the Microsoft Edge browser?

I maintain an old product and I

相关标签:
9条回答
  • 2020-12-05 10:08

    The snippet that I have here is also copy from SO too, am sorry that I could not give you reference for the original code, but I have modified it so here it is for those of you looking for snippet to check for IE 11 and MS Edge Window 10:

    var get_ie_version = function () {
        var sAgent = window.navigator.userAgent;
        var Idx = sAgent.indexOf("MSIE");
    
        // If IE, return version number.
        if (Idx > 0) {
            return parseInt(sAgent.substring(Idx+ 5, sAgent.indexOf(".", Idx)));
        }
        // Condition Check IF IE 11 and or MS Edge
        else if ( !!navigator.userAgent.match(/Trident\/7\./)
            || window.navigator.userAgent.indexOf("Edge") > -1 )
        {
            return 11;
        } else {
            return 0; //It is not IE
        }
    };
    
    0 讨论(0)
  • 2020-12-05 10:10

    The useragent string contains Edge/12.9600, where the 12.9600 is the version number I tested with. This is completely different from the user agent string of Internet Explorer in 'Edge' mode.

    User agent string of Edge:

    Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.135 Safari/537.36 Edge/12.9600

    User agent string of IE10 in Edge mode:

    Mozilla/5.0 (Windows NT 6.3; WOW64; Trident/7.0; .NET4.0E; .NET4.0C; InfoPath.3; .NET CLR 3.5.30729; .NET CLR 2.0.50727; .NET CLR 3.0.30729; Tablet PC 2.0; rv:11.0) like Gecko

    So when using javascript, just check for the word 'Edge' in the user agent string. When you also test for other browsers, make sure you check Edge first, otherwise you will get false positives (for example Chrome or Safari...)

    0 讨论(0)
  • 2020-12-05 10:11

    Try to detect features instead of a specific browser. It's more future-proof. Only rarely should you use browser detection.

    With that out of the way: one option is to use a library (there are many intricacies to User Agent strings), or alternatively to parse window.navigator.userAgent manually.

    Using a parser library

    # https://github.com/faisalman/ua-parser-js.
    
    var parser = new UAParser();
    var result = parser.getResult();
    
    var name = result.browser.name;
    var version = result.browser.version;
    

    Raw approach with Javascript

    # Mozilla/5.0 (Windows NT 10.0) AppleWebKit/537.36 (KHTML, like Gecko) \
    # Chrome/42.0.2311.135 Safari/537.36 Edge/12.10136
    
    window.navigator.userAgent.indexOf("Edge") > -1
    
    0 讨论(0)
提交回复
热议问题