How can you detect the version of a browser?

后端 未结 28 2050
佛祖请我去吃肉
佛祖请我去吃肉 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条回答
  •  有刺的猬
    2020-11-22 00:07

    I wrote a version detector based on Hermann Ingjaldsson's answer, but more robust and which returns an object with name/version data in it. It covers the major browsers but I don't bother with the plethora of mobile ones and minor ones:

    function getBrowserData(nav) {
        var data = {};
    
        var ua = data.uaString = nav.userAgent;
        var browserMatch = ua.match(/(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*([\d\.]+)/i) || [];
        if (browserMatch[1]) { browserMatch[1] = browserMatch[1].toLowerCase(); }
        var operaMatch = browserMatch[1] === 'chrome';
        if (operaMatch) { operaMatch = ua.match(/\bOPR\/([\d\.]+)/); }
    
        if (/trident/i.test(browserMatch[1])) {
            var msieMatch = /\brv[ :]+([\d\.]+)/g.exec(ua) || [];
            data.name = 'msie';
            data.version = msieMatch[1];
        }
        else if (operaMatch) {
            data.name = 'opera';
            data.version = operaMatch[1];
        }
        else if (browserMatch[1] === 'safari') {
            var safariVersionMatch = ua.match(/version\/([\d\.]+)/i);
            data.name = 'safari';
            data.version = safariVersionMatch[1];
        }
        else {
            data.name = browserMatch[1];
            data.version = browserMatch[2];
        }
    
        var versionParts = [];
        if (data.version) {
            var versionPartsMatch = data.version.match(/(\d+)/g) || [];
            for (var i=0; i < versionPartsMatch.length; i++) {
                versionParts.push(versionPartsMatch[i]);
            }
            if (versionParts.length > 0) { data.majorVersion = versionParts[0]; }
        }
        data.name = data.name || '(unknown browser name)';
        data.version = {
            full: data.version || '(unknown full browser version)',
            parts: versionParts,
            major: versionParts.length > 0 ? versionParts[0] : '(unknown major browser version)'
        };
    
        return data;
    };
    

    It can then be used like this:

    var brData = getBrowserData(window.navigator || navigator);
    console.log('name: ' + brData.name);
    console.log('major version: ' + brData.version.major);
    // etc.
    

提交回复
热议问题