How can you detect the version of a browser?

后端 未结 28 2133
佛祖请我去吃肉
佛祖请我去吃肉 2020-11-21 23:35

I\'ve been searching around for code that would let me detect if the user visiting the website has Firefox 3 or 4. All I have found is code to detect the type of browser but

28条回答
  •  梦毁少年i
    2020-11-22 00:23

    Here this has better compatibility then @kennebec snippet;
    will return browser name and version (returns 72 instead of 72.0.3626.96).

    Tested on Safari, Chrome, Opera, Firefox, IE, Edge, UCBrowser, also on mobile.

    function browser() {
        var userAgent = navigator.userAgent,
            match = userAgent.match(/(opera|chrome|crios|safari|ucbrowser|firefox|msie|trident(?=\/))\/?\s*(\d+)/i) || [],
            result = {},
            tem;
    
        if (/trident/i.test(match[1])) {
            tem = /\brv[ :]+(\d+)/g.exec(userAgent) || [];
            result.name = "Internet Explorer";
        } else if (match[1] === "Chrome") {
            tem = userAgent.match(/\b(OPR|Edge)\/(\d+)/);
    
            if (tem && tem[1]) {
                result.name = tem[0].indexOf("Edge") === 0 ? "Edge" : "Opera";
            }
        }
        if (!result.name) {
            tem = userAgent.match(/version\/(\d+)/i); // iOS support
            result.name = match[0].replace(/\/.*/, "");
    
            if (result.name.indexOf("MSIE") === 0) {
                result.name = "Internet Explorer";
            }
            if (userAgent.match("CriOS")) {
                result.name = "Chrome";
            }
    
        }
        if (tem && tem.length) {
            match[match.length - 1] = tem[tem.length - 1];
        }
    
        result.version = Number(match[match.length - 1]);
    
        return result;
    }
    

提交回复
热议问题