如何检测浏览器的版本?

发布于 2024-11-05 06:50:40 字数 99 浏览 5 评论 0原文

我一直在寻找可以让我检测访问网站的用户是否使用 Firefox 3 或 4 的代码。我找到的只是检测浏览器类型的代码,而不是检测版本的代码。

如何检测这样的浏览器版本?

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 not the version.

How can I detect the version of a browser like this?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(30

許願樹丅啲祈禱 2024-11-12 06:50:41

我想分享我为必须解决的问题编写的代码。它在大多数主要浏览器中进行了测试,对我来说就像一个魅力!

看起来这段代码与其他答案非常相似,但它进行了修改,以便我可以使用它插入 jquery 中的浏览器对象,这是我最近错过的,当然它是上述代码的组合,几乎没有改进我所做的部分:

(function($, ua){

var M = ua.match(/(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i) || [],
    tem, 
    res;

if(/trident/i.test(M[1])){
    tem = /\brv[ :]+(\d+)/g.exec(ua) || [];
    res = 'IE ' + (tem[1] || '');
}
else if(M[1] === 'Chrome'){
    tem = ua.match(/\b(OPR|Edge)\/(\d+)/);
    if(tem != null) 
        res = tem.slice(1).join(' ').replace('OPR', 'Opera');
    else
        res = [M[1], M[2]];
}
else {
    M = M[2]? [M[1], M[2]] : [navigator.appName, navigator.appVersion, '-?'];
    if((tem = ua.match(/version\/(\d+)/i)) != null) M = M.splice(1, 1, tem[1]);
    res = M;
}

res = typeof res === 'string'? res.split(' ') : res;

$.browser = {
    name: res[0],
    version: res[1],
    msie: /msie|ie/i.test(res[0]),
    firefox: /firefox/i.test(res[0]),
    opera: /opera/i.test(res[0]),
    chrome: /chrome/i.test(res[0]),
    edge: /edge/i.test(res[0])
}

})(typeof jQuery != 'undefined'? jQuery : window.$, navigator.userAgent);

 console.log($.browser.name, $.browser.version, $.browser.msie); 
// if IE 11 output is: IE 11 true

I want to share this code I wrote for the issue I had to resolve. It was tested in most of the major browsers and works like a charm, for me!

It may seems that this code is very similar to the other answers but it modifyed so that I can use it insted of the browser object in jquery which missed for me recently, of course it is a combination from the above codes, with little improvements from my part I made:

(function($, ua){

var M = ua.match(/(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i) || [],
    tem, 
    res;

if(/trident/i.test(M[1])){
    tem = /\brv[ :]+(\d+)/g.exec(ua) || [];
    res = 'IE ' + (tem[1] || '');
}
else if(M[1] === 'Chrome'){
    tem = ua.match(/\b(OPR|Edge)\/(\d+)/);
    if(tem != null) 
        res = tem.slice(1).join(' ').replace('OPR', 'Opera');
    else
        res = [M[1], M[2]];
}
else {
    M = M[2]? [M[1], M[2]] : [navigator.appName, navigator.appVersion, '-?'];
    if((tem = ua.match(/version\/(\d+)/i)) != null) M = M.splice(1, 1, tem[1]);
    res = M;
}

res = typeof res === 'string'? res.split(' ') : res;

$.browser = {
    name: res[0],
    version: res[1],
    msie: /msie|ie/i.test(res[0]),
    firefox: /firefox/i.test(res[0]),
    opera: /opera/i.test(res[0]),
    chrome: /chrome/i.test(res[0]),
    edge: /edge/i.test(res[0])
}

})(typeof jQuery != 'undefined'? jQuery : window.$, navigator.userAgent);

 console.log($.browser.name, $.browser.version, $.browser.msie); 
// if IE 11 output is: IE 11 true
浅语花开 2024-11-12 06:50:41
navigator.sayswho= (function(){
    var ua= navigator.userAgent, tem, 
    M= ua.match(/(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i) || [];
    if(/trident/i.test(M[1])){
        tem=  /\brv[ :]+(\d+)/g.exec(ua) || [];
        return 'IE '+(tem[1] || '');
    }
    if(M[1]=== 'Chrome'){
        tem= ua.match(/\b(OPR|Edge)\/(\d+)/);
        if(tem!= null) return tem.slice(1).join(' ').replace('OPR', 'Opera');
    }
    M= M[2]? [M[1], M[2]]: [navigator.appName, navigator.appVersion, '-?'];
    if((tem= ua.match(/version\/(\d+)/i))!= null) M.splice(1, 1, tem[1]);
    return M.join(' ');
})();

console.log(navigator.sayswho); // outputs: `Chrome 62`

navigator.sayswho= (function(){
    var ua= navigator.userAgent, tem, 
    M= ua.match(/(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i) || [];
    if(/trident/i.test(M[1])){
        tem=  /\brv[ :]+(\d+)/g.exec(ua) || [];
        return 'IE '+(tem[1] || '');
    }
    if(M[1]=== 'Chrome'){
        tem= ua.match(/\b(OPR|Edge)\/(\d+)/);
        if(tem!= null) return tem.slice(1).join(' ').replace('OPR', 'Opera');
    }
    M= M[2]? [M[1], M[2]]: [navigator.appName, navigator.appVersion, '-?'];
    if((tem= ua.match(/version\/(\d+)/i))!= null) M.splice(1, 1, tem[1]);
    return M.join(' ');
})();

console.log(navigator.sayswho); // outputs: `Chrome 62`

滥情稳全场 2024-11-12 06:50:41

我用它来获取实际浏览器版本的名称和编号(int):

function getInfoBrowser() {
    var ua = navigator.userAgent, tem,
    M = ua.match(/(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i) || [];
    if (/trident/i.test(M[1])) {
        tem = /\brv[ :]+(\d+)/g.exec(ua) || [];
        return { name: 'Explorer', version: parseInt((tem[1] || '')) };
    }
    if (M[1] === 'Chrome') {
        tem = ua.match(/\b(OPR|Edge)\/(\d+)/);
        if (tem != null) { let app = tem.slice(1).toString().split(','); return { name: app[0].replace('OPR', 'Opera'), version: parseInt(app[1]) }; }
    }
    M = M[2] ? [M[1], M[2]] : [navigator.appName, navigator.appVersion, '-?'];
    if ((tem = ua.match(/version\/(\d+)/i)) != null) M.splice(1, 1, tem[1]);
    return {
        name: M[0],
        version: parseInt(M[1])
    };
}

function getBrowser(){
  let info = getInfoBrowser();
  $("#i-name").html(info.name);
  $("#i-version").html(info.version);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<input type="button" onclick="getBrowser();" value="Get Info Browser"/>
<hr/>
Name: <span id="i-name"></span><br/>
Version: <span id="i-version"></span>

这在

Chrome 中运行;火狐浏览器;野生动物园; Internet Explorer (>= 9) ;歌剧;边缘

对我来说。

I use this to get de Name and number (int) of the version of the actual browser:

function getInfoBrowser() {
    var ua = navigator.userAgent, tem,
    M = ua.match(/(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i) || [];
    if (/trident/i.test(M[1])) {
        tem = /\brv[ :]+(\d+)/g.exec(ua) || [];
        return { name: 'Explorer', version: parseInt((tem[1] || '')) };
    }
    if (M[1] === 'Chrome') {
        tem = ua.match(/\b(OPR|Edge)\/(\d+)/);
        if (tem != null) { let app = tem.slice(1).toString().split(','); return { name: app[0].replace('OPR', 'Opera'), version: parseInt(app[1]) }; }
    }
    M = M[2] ? [M[1], M[2]] : [navigator.appName, navigator.appVersion, '-?'];
    if ((tem = ua.match(/version\/(\d+)/i)) != null) M.splice(1, 1, tem[1]);
    return {
        name: M[0],
        version: parseInt(M[1])
    };
}

function getBrowser(){
  let info = getInfoBrowser();
  $("#i-name").html(info.name);
  $("#i-version").html(info.version);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<input type="button" onclick="getBrowser();" value="Get Info Browser"/>
<hr/>
Name: <span id="i-name"></span><br/>
Version: <span id="i-version"></span>

This run in

Chrome ; Firefox ; Safari ; Internet Explorer (>= 9) ; Opera ; Edge

For me.

心如狂蝶 2024-11-12 06:50:41

对于任何使用 Angular 的 PWA 应用程序,您可以在 index.html 的正文部分中放置代码来检查浏览器是否受支持 -

<body>
    <div id="browser"></div>
    <script>
        var operabrowser = true;
        operabrowser = (navigator.userAgent.indexOf('Opera Mini') > -1);
        if (operabrowser) {
            txt = "<p>Browser not supported use different browser...</p>";
            document.getElementById("browser").innerHTML = txt;
        }
    </script>
</body>

For any PWA application using angular you can put the code to check if browser is supported or not in body section of index.html -

<body>
    <div id="browser"></div>
    <script>
        var operabrowser = true;
        operabrowser = (navigator.userAgent.indexOf('Opera Mini') > -1);
        if (operabrowser) {
            txt = "<p>Browser not supported use different browser...</p>";
            document.getElementById("browser").innerHTML = txt;
        }
    </script>
</body>
江南烟雨〆相思醉 2024-11-12 06:50:41

根据接受的答案,这是用于检测“Microsoft Edge”的更新

navigator.sayswho= (function(){
    var ua= navigator.userAgent;
    var tem; 
    var M= ua.match(/(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i) || [];
    if(/trident/i.test(M[1])){
        tem=  /\brv[ :]+(\d+)/g.exec(ua) || [];
        return 'IE '+(tem[1] || '');
    }
    if(M[1]=== 'Chrome'){
        tem= ua.match(/\b(OPR|Edg)\/(\d+)/);
        if(tem!= null) return tem.slice(1).join(' ').replace('OPR', 'Opera');
    }
    M= M[2]? [M[1], M[2]]: [navigator.appName, navigator.appVersion, '-?'];
    if((tem= ua.match(/version\/(\d+)/i))!= null) M.splice(1, 1, tem[1]);
    return M.join(' ');
})();

console.log(navigator.sayswho); 

Based on the accepted answer, this is an update for detecting "Microsoft Edge"

navigator.sayswho= (function(){
    var ua= navigator.userAgent;
    var tem; 
    var M= ua.match(/(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i) || [];
    if(/trident/i.test(M[1])){
        tem=  /\brv[ :]+(\d+)/g.exec(ua) || [];
        return 'IE '+(tem[1] || '');
    }
    if(M[1]=== 'Chrome'){
        tem= ua.match(/\b(OPR|Edg)\/(\d+)/);
        if(tem!= null) return tem.slice(1).join(' ').replace('OPR', 'Opera');
    }
    M= M[2]? [M[1], M[2]]: [navigator.appName, navigator.appVersion, '-?'];
    if((tem= ua.match(/version\/(\d+)/i))!= null) M.splice(1, 1, tem[1]);
    return M.join(' ');
})();

console.log(navigator.sayswho); 

失而复得 2024-11-12 06:50:41

用于检测 iOS 浏览器的更新代码。

navigator.sayswho= (function(){
var ua= navigator.userAgent;
var tem; 
var M= ua.match(/(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i) || [];
if(/trident/i.test(M[1])){
    tem=  /\brv[ :]+(\d+)/g.exec(ua) || [];
    return 'IE '+(tem[1] || '');
}
if(M[1]=== 'Chrome'){
    tem= ua.match(/\b(OPR)\/(\d+)/);
    if(tem!= null) return 'Opera '+ tem.slice(1)[1];
    tem= ua.match(/\b(Edg[a-zA-Z]{0,3})\/(\d+)/);
    if(tem!= null) return 'Edge '+ tem.slice(1)[1];
} else if(M[1]=== 'Safari') {
    tem= ua.match(/\b(EdgiOS)\/(\d+)/);
    if(tem!= null) return 'Edge '+ tem.slice(1)[1];
    tem= ua.match(/\b(FxiOS)\/(\d+)/);
    if(tem!= null) return 'Firefox '+ tem.slice(1)[1];
    tem= ua.match(/\b(CriOS)\/(\d+)/);
    if(tem!= null) return 'Chrome '+ tem.slice(1)[1];
} 
M= M[2]? [M[1], M[2]]: [navigator.appName, navigator.appVersion, '-?'];
if((tem= ua.match(/version\/(\d+)/i))!= null) M.splice(1, 1, tem[1]);
return M.join(' ');

})();

An updated code to detect browsers from iOS.

navigator.sayswho= (function(){
var ua= navigator.userAgent;
var tem; 
var M= ua.match(/(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i) || [];
if(/trident/i.test(M[1])){
    tem=  /\brv[ :]+(\d+)/g.exec(ua) || [];
    return 'IE '+(tem[1] || '');
}
if(M[1]=== 'Chrome'){
    tem= ua.match(/\b(OPR)\/(\d+)/);
    if(tem!= null) return 'Opera '+ tem.slice(1)[1];
    tem= ua.match(/\b(Edg[a-zA-Z]{0,3})\/(\d+)/);
    if(tem!= null) return 'Edge '+ tem.slice(1)[1];
} else if(M[1]=== 'Safari') {
    tem= ua.match(/\b(EdgiOS)\/(\d+)/);
    if(tem!= null) return 'Edge '+ tem.slice(1)[1];
    tem= ua.match(/\b(FxiOS)\/(\d+)/);
    if(tem!= null) return 'Firefox '+ tem.slice(1)[1];
    tem= ua.match(/\b(CriOS)\/(\d+)/);
    if(tem!= null) return 'Chrome '+ tem.slice(1)[1];
} 
M= M[2]? [M[1], M[2]]: [navigator.appName, navigator.appVersion, '-?'];
if((tem= ua.match(/version\/(\d+)/i))!= null) M.splice(1, 1, tem[1]);
return M.join(' ');

})();

爱*していゐ 2024-11-12 06:50:41
var ua = navigator.userAgent;

if (/Firefox\//.test(ua))
   var Firefox = /Firefox\/([0-9\.A-z]+)/.exec(ua)[1];
var ua = navigator.userAgent;

if (/Firefox\//.test(ua))
   var Firefox = /Firefox\/([0-9\.A-z]+)/.exec(ua)[1];
极致的悲 2024-11-12 06:50:41

我写这个是为了我的需要。

它获取诸如是否是移动设备或是否具有视网膜显示屏之类的信息

尝试一下

var nav = {
        isMobile:function(){
            return (navigator.userAgent.match(/iPhone|iPad|iPod|Android|BlackBerry|Opera Mini|IEMobile/i) != null);
        },
        isDesktop:function(){
            return (navigator.userAgent.match(/iPhone|iPad|iPod|Android|BlackBerry|Opera Mini|IEMobile/i) == null);
        },
        isAndroid: function() {
            return navigator.userAgent.match(/Android/i);
        },
        isBlackBerry: function() {
            return navigator.userAgent.match(/BlackBerry/i);
        },
        isIOS: function() {
            return navigator.userAgent.match(/iPhone|iPad|iPod/i);
        },
        isOpera: function() {
            return navigator.userAgent.match(/Opera Mini/i);
        },
        isWindows: function() {
            return navigator.userAgent.match(/IEMobile/i);
        },
        isRetina:function(){
            return window.devicePixelRatio && window.devicePixelRatio > 1;
        },
        isIPad:function(){
            isIPad = (/ipad/gi).test(navigator.platform);
            return isIPad;
        },
        isLandscape:function(){
            if(window.innerHeight < window.innerWidth){
                return true;
            }
            return false;
        },
        getIOSVersion:function(){
            if(this.isIOS()){
                var OSVersion = navigator.appVersion.match(/OS (\d+_\d+)/i);
                OSVersion = OSVersion[1] ? +OSVersion[1].replace('_', '.') : 0;
                return OSVersion;
            }
            else
                return false;
        },
        isStandAlone:function(){
            if(_.is(navigator.standalone))
                return navigator.standalone;
            return false;
        },
        isChrome:function(){
            var isChrome = (/Chrome/gi).test(navigator.appVersion);
            var isSafari = (/Safari/gi).test(navigator.appVersion)
            return isChrome && isSafari;
        },
        isSafari:function(){
            var isSafari = (/Safari/gi).test(navigator.appVersion)
            var isChrome = (/Chrome/gi).test(navigator.appVersion)
            return !isChrome && isSafari;
        }
}

I wrote this for my needs.

It get info like if is a mobile device or if has a retina display

try it

var nav = {
        isMobile:function(){
            return (navigator.userAgent.match(/iPhone|iPad|iPod|Android|BlackBerry|Opera Mini|IEMobile/i) != null);
        },
        isDesktop:function(){
            return (navigator.userAgent.match(/iPhone|iPad|iPod|Android|BlackBerry|Opera Mini|IEMobile/i) == null);
        },
        isAndroid: function() {
            return navigator.userAgent.match(/Android/i);
        },
        isBlackBerry: function() {
            return navigator.userAgent.match(/BlackBerry/i);
        },
        isIOS: function() {
            return navigator.userAgent.match(/iPhone|iPad|iPod/i);
        },
        isOpera: function() {
            return navigator.userAgent.match(/Opera Mini/i);
        },
        isWindows: function() {
            return navigator.userAgent.match(/IEMobile/i);
        },
        isRetina:function(){
            return window.devicePixelRatio && window.devicePixelRatio > 1;
        },
        isIPad:function(){
            isIPad = (/ipad/gi).test(navigator.platform);
            return isIPad;
        },
        isLandscape:function(){
            if(window.innerHeight < window.innerWidth){
                return true;
            }
            return false;
        },
        getIOSVersion:function(){
            if(this.isIOS()){
                var OSVersion = navigator.appVersion.match(/OS (\d+_\d+)/i);
                OSVersion = OSVersion[1] ? +OSVersion[1].replace('_', '.') : 0;
                return OSVersion;
            }
            else
                return false;
        },
        isStandAlone:function(){
            if(_.is(navigator.standalone))
                return navigator.standalone;
            return false;
        },
        isChrome:function(){
            var isChrome = (/Chrome/gi).test(navigator.appVersion);
            var isSafari = (/Safari/gi).test(navigator.appVersion)
            return isChrome && isSafari;
        },
        isSafari:function(){
            var isSafari = (/Safari/gi).test(navigator.appVersion)
            var isChrome = (/Chrome/gi).test(navigator.appVersion)
            return !isChrome && isSafari;
        }
}
雨轻弹 2024-11-12 06:50:41

我根据在其他帖子中找到的内容使用这段 JavaScript 代码。

var browserHelper = function () {
    var self = {};

    /// IE 6+
    self.isIEBrowser = function () {
        return /*@cc_on!@*/false || !!document.documentMode;
    };

    /// Opera 8.0+
    self.isOperaBrowser = function () {
        return (!!window.opr && !!opr.addons)
            || !!window.opera
            || navigator.userAgent.indexOf(' OPR/') >= 0;
    };

    /// Firefox 1.0+
    self.isFirefoxBrowser = function () {
        return typeof InstallTrigger !== 'undefined';
    };

    /// Safari 3.0+
    self.isSafariBrowser = function () {
        return /constructor/i.test(window.HTMLElement)
            || (function (p) { return p.toString() === "[object SafariRemoteNotification]"; })(!window['safari'] || (typeof safari !== 'undefined' && window['safari'].pushNotification));
    };

    /// Edge 20+
    self.isEdgeBrowser = function () {
        return !self.isIEBrowser() && !!window.StyleMedia;
    };

    /// Chrome 1 - 87
    self.isChromeBrowser = function () {
        return (!!window.chrome && (!!window.chrome.webstore || !!window.chrome.runtime))
            || (navigator.userAgent.indexOf("Chrome") > -1) && !self.isOperaBrowser();
    };

    /// Edge (based on chromium)
    self.isEdgeChromiumBrowser = function () {
        return self.isChromeBrowser() && (navigator.userAgent.indexOf("Edg") != -1);
    };

    /// Blink
    self.isBlinkBasedOnBrowser = function () {
        return (self.isChromeBrowser() || self.isOperaBrowser()) && !!window.CSS;
    };

    /// Returns the name of the navigator
    self.browserName = function () {

        if (self.isOperaBrowser()) return "Opera";

        if (self.isEdgeBrowser()) return "Edge";

        if (self.isEdgeChromiumBrowser()) return "Edge (based on chromium)";

        if (self.isFirefoxBrowser()) return "Firefox";

        if (self.isIEBrowser()) return "Internet Explorer";

        if (self.isSafariBrowser()) return "Safari";

        if (self.isChromeBrowser()) return "Chrome";

        return "Unknown";
    };
    
    return self;
};

var bName = document.getElementById('browserName');
bName.innerText = browserHelper().browserName();
#browserName {
  font-family: Arial, Verdana;
  font-size: 1.2rem;
  color: #ff8000;
  text-align: center;
  border: 2px solid #ff8000;
  border-radius: .5rem;
  padding: .5rem;
  max-width: 25%;
  margin: auto;
}
<div id="browserName"></div>

I use this piece of javascript code based on what I could find in another posts.

var browserHelper = function () {
    var self = {};

    /// IE 6+
    self.isIEBrowser = function () {
        return /*@cc_on!@*/false || !!document.documentMode;
    };

    /// Opera 8.0+
    self.isOperaBrowser = function () {
        return (!!window.opr && !!opr.addons)
            || !!window.opera
            || navigator.userAgent.indexOf(' OPR/') >= 0;
    };

    /// Firefox 1.0+
    self.isFirefoxBrowser = function () {
        return typeof InstallTrigger !== 'undefined';
    };

    /// Safari 3.0+
    self.isSafariBrowser = function () {
        return /constructor/i.test(window.HTMLElement)
            || (function (p) { return p.toString() === "[object SafariRemoteNotification]"; })(!window['safari'] || (typeof safari !== 'undefined' && window['safari'].pushNotification));
    };

    /// Edge 20+
    self.isEdgeBrowser = function () {
        return !self.isIEBrowser() && !!window.StyleMedia;
    };

    /// Chrome 1 - 87
    self.isChromeBrowser = function () {
        return (!!window.chrome && (!!window.chrome.webstore || !!window.chrome.runtime))
            || (navigator.userAgent.indexOf("Chrome") > -1) && !self.isOperaBrowser();
    };

    /// Edge (based on chromium)
    self.isEdgeChromiumBrowser = function () {
        return self.isChromeBrowser() && (navigator.userAgent.indexOf("Edg") != -1);
    };

    /// Blink
    self.isBlinkBasedOnBrowser = function () {
        return (self.isChromeBrowser() || self.isOperaBrowser()) && !!window.CSS;
    };

    /// Returns the name of the navigator
    self.browserName = function () {

        if (self.isOperaBrowser()) return "Opera";

        if (self.isEdgeBrowser()) return "Edge";

        if (self.isEdgeChromiumBrowser()) return "Edge (based on chromium)";

        if (self.isFirefoxBrowser()) return "Firefox";

        if (self.isIEBrowser()) return "Internet Explorer";

        if (self.isSafariBrowser()) return "Safari";

        if (self.isChromeBrowser()) return "Chrome";

        return "Unknown";
    };
    
    return self;
};

var bName = document.getElementById('browserName');
bName.innerText = browserHelper().browserName();
#browserName {
  font-family: Arial, Verdana;
  font-size: 1.2rem;
  color: #ff8000;
  text-align: center;
  border: 2px solid #ff8000;
  border-radius: .5rem;
  padding: .5rem;
  max-width: 25%;
  margin: auto;
}
<div id="browserName"></div>

豆芽 2024-11-12 06:50:40

您可以查看浏览器所说的内容,并使用该信息来记录或测试多个浏览器。

navigator.sayswho= (function(){
    var ua= navigator.userAgent;
    var tem; 
    var M= ua.match(/(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i) || [];
    if(/trident/i.test(M[1])){
        tem=  /\brv[ :]+(\d+)/g.exec(ua) || [];
        return 'IE '+(tem[1] || '');
    }
    if(M[1]=== 'Chrome'){
        tem= ua.match(/\b(OPR|Edge)\/(\d+)/);
        if(tem!= null) return tem.slice(1).join(' ').replace('OPR', 'Opera');
    }
    M= M[2]? [M[1], M[2]]: [navigator.appName, navigator.appVersion, '-?'];
    if((tem= ua.match(/version\/(\d+)/i))!= null) M.splice(1, 1, tem[1]);
    return M.join(' ');
})();

console.log(navigator.sayswho); // outputs: `Chrome 62`

You can see what the browser says, and use that information for logging or testing multiple browsers.

navigator.sayswho= (function(){
    var ua= navigator.userAgent;
    var tem; 
    var M= ua.match(/(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i) || [];
    if(/trident/i.test(M[1])){
        tem=  /\brv[ :]+(\d+)/g.exec(ua) || [];
        return 'IE '+(tem[1] || '');
    }
    if(M[1]=== 'Chrome'){
        tem= ua.match(/\b(OPR|Edge)\/(\d+)/);
        if(tem!= null) return tem.slice(1).join(' ').replace('OPR', 'Opera');
    }
    M= M[2]? [M[1], M[2]]: [navigator.appName, navigator.appVersion, '-?'];
    if((tem= ua.match(/version\/(\d+)/i))!= null) M.splice(1, 1, tem[1]);
    return M.join(' ');
})();

console.log(navigator.sayswho); // outputs: `Chrome 62`

决绝 2024-11-12 06:50:40

这是对肯纳贝克答案的改进。

mbrowser=function(){
    this.spec_string=   navigator.userAgent;
    this.name=          this.get_name();
    this.version=       this.get_version();
    };

mbrowser.prototype.get_name=function(){
    var spec_string=this.spec_string;

    var matches=spec_string.match(/(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i) || [];
    
    // Work with the matches.
    matches=matches[2]? [matches[1], matches[2]]: [navigator.appName, navigator.appVersion, '-?'];
        
    // Trident.
    if(/trident/i.test(matches[1])){
        var temp=/\brv[ :]+(\d+)/g.exec(spec_string) || [];
        return 'IE';
        }
    
    // Chrome.
    if(matches[1]==='Chrome'){
        var temp=spec_string.match(/\bOPR|Edge\/(\d+)/)
        if(temp!=null)   {return 'Opera';}
        }   

    if((temp=spec_string.match(/version\/(\d+)/i))!=null){
        matches.splice(1,1,temp[1]);
        }
                                                                                                                       
    var name=matches[0];

    return name;
    };


mbrowser.prototype.get_version=function(){
    var spec_string=this.spec_string;

    var matches=spec_string.match(/(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i) || []; 

    // Work with the matches.
    matches=matches[2]? [matches[1], matches[2]]: [navigator.appName, navigator.appVersion, '-?'];

    // Trident.
    if(/trident/i.test(matches[1])){
        var temp=/\brv[ :]+(\d+)/g.exec(spec_string) || []; 
        var version=(temp[1]||'');
        return version;
        }   

    // Chrome.
    if(matches[1]==='Chrome'){
        var temp=spec_string.match(/\bOPR|Edge\/(\d+)/)
        var version=temp[1];
        if(temp!=null)   {return version;}
        }   

    if((temp=spec_string.match(/version\/(\d+)/i))!=null){
        matches.splice(1,1,temp[1]);                                                                                   
        }

    var version=matches[1];

    return version;
    };

// m=module.
var browser=new mbrowser();
console.log(browser.name);    // Chrome
console.log(browser.version); // 109

此代码从spec_string (navigator.userAgent) 推导出浏览器名称和编号。但是有各种各样的spec_strings 以及它们各自的浏览器名称和编号。我无法检查其中的一小部分。如果您可以发布一个您知道其生成的浏览器名称和编号的spec_string,那就太好了。然后我可以相应地更新代码。

然后,我将按以下方式慢慢建立一个spec_string项目列表。

'spec_string1'=>[name,number],
'spec_string2'=>[name,number],

将来,每当对代码进行更改时,都可以自动对所有已知的 spec_string 转换进行测试。

我们可以一起做这件事。

This is an improvement on Kennebec's answer.

mbrowser=function(){
    this.spec_string=   navigator.userAgent;
    this.name=          this.get_name();
    this.version=       this.get_version();
    };

mbrowser.prototype.get_name=function(){
    var spec_string=this.spec_string;

    var matches=spec_string.match(/(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i) || [];
    
    // Work with the matches.
    matches=matches[2]? [matches[1], matches[2]]: [navigator.appName, navigator.appVersion, '-?'];
        
    // Trident.
    if(/trident/i.test(matches[1])){
        var temp=/\brv[ :]+(\d+)/g.exec(spec_string) || [];
        return 'IE';
        }
    
    // Chrome.
    if(matches[1]==='Chrome'){
        var temp=spec_string.match(/\bOPR|Edge\/(\d+)/)
        if(temp!=null)   {return 'Opera';}
        }   

    if((temp=spec_string.match(/version\/(\d+)/i))!=null){
        matches.splice(1,1,temp[1]);
        }
                                                                                                                       
    var name=matches[0];

    return name;
    };


mbrowser.prototype.get_version=function(){
    var spec_string=this.spec_string;

    var matches=spec_string.match(/(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i) || []; 

    // Work with the matches.
    matches=matches[2]? [matches[1], matches[2]]: [navigator.appName, navigator.appVersion, '-?'];

    // Trident.
    if(/trident/i.test(matches[1])){
        var temp=/\brv[ :]+(\d+)/g.exec(spec_string) || []; 
        var version=(temp[1]||'');
        return version;
        }   

    // Chrome.
    if(matches[1]==='Chrome'){
        var temp=spec_string.match(/\bOPR|Edge\/(\d+)/)
        var version=temp[1];
        if(temp!=null)   {return version;}
        }   

    if((temp=spec_string.match(/version\/(\d+)/i))!=null){
        matches.splice(1,1,temp[1]);                                                                                   
        }

    var version=matches[1];

    return version;
    };

// m=module.
var browser=new mbrowser();
console.log(browser.name);    // Chrome
console.log(browser.version); // 109

This code deduces browser name and number from the spec_string (navigator.userAgent). But there are all kinds of spec_strings out there with their respective browser name and number. And I'm not in a situation to check but a tiny proportion of them. It would be great if you could post a spec_string whose resulting browser name and number you know. I can then update the code accordingly.

I would then slowly build up a list of spec_string items in the following manner.

'spec_string1'=>[name,number],
'spec_string2'=>[name,number],

Then in the future, whenever a change is made to the code it can automatically be tested on all known spec_string conversions.

We can do this together.

墨小沫ゞ 2024-11-12 06:50:40

以下是截至 2019 年 5 月处理浏览器检测的几个著名库。

Bowser 作者:lancedikson - 3,761★s - 最后更新于 2019 年 5 月 26 日 - 4.8KB

var result = bowser.getParser(window.navigator.userAgent);
console.log(result);
document.write("You are using " + result.parsedResult.browser.name +
               " v" + result.parsedResult.browser.version + 
               " on " + result.parsedResult.os.name);
<script src="https://unpkg.com/[email protected]/es5.js"></script>

*支持基于 Chromium 的 Edge


Platform.js by bestiejs - 2,250 ★s - 最后更新于 2018 年 10 月 30 日 - 5.9KB

console.log(platform);
document.write("You are using " + platform.name +
               " v" + platform.version + 
               " on " + platform.os);
<script src="https://cdnjs.cloudflare.com/ajax/libs/platform/1.3.5/platform.min.js"></script>

jQuery 浏览器 作者:gabceb - 504★s - 最后更新时间:2015 年 11 月 23 日 - 1.3KB

console.log($.browser)
document.write("You are using " + $.browser.name +
               " v" + $.browser.versionNumber + 
               " on " + $.browser.platform);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-browser/0.1.0/jquery.browser.min.js"></script>

Detect.js(已存档) 作者:darcyclarke - 522★s - 最后更新时间:2015 年 10 月 26 日 - 2.9知识库

var result = detect.parse(navigator.userAgent);
console.log(result);
document.write("You are using " + result.browser.family +
               " v" + result.browser.version + 
               " on " + result.os.family);
<script src="https://cdnjs.cloudflare.com/ajax/libs/Detect.js/2.2.2/detect.min.js"></script>

浏览器检测(已存档) 由 QuirksMode 撰写 - 最后更新于 2013 年 11 月 14 日 - 884B

console.log(BrowserDetect)
document.write("You are using " + BrowserDetect.browser +
               " v" + BrowserDetect.version + 
               " on " + BrowserDetect.OS);
<script src="https://kylemit.github.io/libraries/libraries/BrowserDetect.js"></script>


值得注意的提及:

  • WhichBrowser - 1,355★s - 最后更新于 2018 年 10 月 2 日
  • Modernizr - 23,397★s - 最后更新于 2019 年 1 月 12 日 - 为了喂养喂饱的马,特征检测应该驱动任何 canIuse 风格的问题。浏览器检测实际上只是为各个浏览器提供定制图像、下载文件或说明。

进一步阅读

Here are several prominent libraries that handle browser detection as of May 2019.

Bowser by lancedikson - 3,761★s - Last updated May 26, 2019 - 4.8KB

var result = bowser.getParser(window.navigator.userAgent);
console.log(result);
document.write("You are using " + result.parsedResult.browser.name +
               " v" + result.parsedResult.browser.version + 
               " on " + result.parsedResult.os.name);
<script src="https://unpkg.com/[email protected]/es5.js"></script>

*supports Edge based on Chromium


Platform.js by bestiejs - 2,250★s - Last updated Oct 30, 2018 - 5.9KB

console.log(platform);
document.write("You are using " + platform.name +
               " v" + platform.version + 
               " on " + platform.os);
<script src="https://cdnjs.cloudflare.com/ajax/libs/platform/1.3.5/platform.min.js"></script>

jQuery Browser by gabceb - 504★s - Last updated Nov 23, 2015 - 1.3KB

console.log($.browser)
document.write("You are using " + $.browser.name +
               " v" + $.browser.versionNumber + 
               " on " + $.browser.platform);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-browser/0.1.0/jquery.browser.min.js"></script>

Detect.js (Archived) by darcyclarke - 522★s - Last updated Oct 26, 2015 - 2.9KB

var result = detect.parse(navigator.userAgent);
console.log(result);
document.write("You are using " + result.browser.family +
               " v" + result.browser.version + 
               " on " + result.os.family);
<script src="https://cdnjs.cloudflare.com/ajax/libs/Detect.js/2.2.2/detect.min.js"></script>

Browser Detect (Archived) by QuirksMode - Last updated Nov 14, 2013 - 884B

console.log(BrowserDetect)
document.write("You are using " + BrowserDetect.browser +
               " v" + BrowserDetect.version + 
               " on " + BrowserDetect.OS);
<script src="https://kylemit.github.io/libraries/libraries/BrowserDetect.js"></script>


Notable Mentions:

  • WhichBrowser - 1,355★s - Last updated Oct 2, 2018
  • Modernizr - 23,397★s - Last updated Jan 12, 2019 - To feed a fed horse, feature detection should drive any canIuse style questions. Browser detection is really just for providing customized images, download files, or instructions for individual browsers.

Further Reading

如梦亦如幻 2024-11-12 06:50:40

这结合了肯纳贝克(K)的答案和赫尔曼·英雅德森(H)的答案:

  • 保持原始答案的最小代码。 (K)
  • 与 Microsoft Edge 配合使用 (K)
  • 扩展导航器对象而不是创建新的变量/对象。 (K)
  • 将浏览器版本和名称分离为独立的子对象。 (H)

 

    navigator.browserSpecs = (function(){
        var ua = navigator.userAgent, tem, 
            M = ua.match(/(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i) || [];
        if(/trident/i.test(M[1])){
            tem = /\brv[ :]+(\d+)/g.exec(ua) || [];
            return {name:'IE',version:(tem[1] || '')};
        }
        if(M[1]=== 'Chrome'){
            tem = ua.match(/\b(OPR|Edge)\/(\d+)/);
            if(tem != null) return {name:tem[1].replace('OPR', 'Opera'),version:tem[2]};
        }
        M = M[2]? [M[1], M[2]]: [navigator.appName, navigator.appVersion, '-?'];
        if((tem = ua.match(/version\/(\d+)/i))!= null)
            M.splice(1, 1, tem[1]);
        return {name:M[0], version:M[1]};
    })();

    console.log(navigator.browserSpecs); //Object { name: "Firefox", version: "42" }

    if (navigator.browserSpecs.name == 'Firefox') {
        // Do something for Firefox.
        if (navigator.browserSpecs.version > 42) {
            // Do something for Firefox versions greater than 42.
        }
    }
    else {
        // Do something for all other browsers.
    }

This combines kennebec's (K) answer with Hermann Ingjaldsson's (H) answer:

  • Maintains original answer's minimal code. (K)
  • Works with Microsoft Edge (K)
  • Extends the navigator object instead of creating a new variable/object. (K)
  • Separates browser version and name into independent child objects. (H)

    navigator.browserSpecs = (function(){
        var ua = navigator.userAgent, tem, 
            M = ua.match(/(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i) || [];
        if(/trident/i.test(M[1])){
            tem = /\brv[ :]+(\d+)/g.exec(ua) || [];
            return {name:'IE',version:(tem[1] || '')};
        }
        if(M[1]=== 'Chrome'){
            tem = ua.match(/\b(OPR|Edge)\/(\d+)/);
            if(tem != null) return {name:tem[1].replace('OPR', 'Opera'),version:tem[2]};
        }
        M = M[2]? [M[1], M[2]]: [navigator.appName, navigator.appVersion, '-?'];
        if((tem = ua.match(/version\/(\d+)/i))!= null)
            M.splice(1, 1, tem[1]);
        return {name:M[0], version:M[1]};
    })();

    console.log(navigator.browserSpecs); //Object { name: "Firefox", version: "42" }

    if (navigator.browserSpecs.name == 'Firefox') {
        // Do something for Firefox.
        if (navigator.browserSpecs.version > 42) {
            // Do something for Firefox versions greater than 42.
        }
    }
    else {
        // Do something for all other browsers.
    }

把回忆走一遍 2024-11-12 06:50:40

bowser JavaScript 库提供了此功能。

if (bowser.msie && bowser.version <= 6) {
  alert('Hello China');
}

看起来保养得很好。

The bowser JavaScript library offers this functionality.

if (bowser.msie && bowser.version <= 6) {
  alert('Hello China');
}

It seems to be well maintained.

就像说晚安 2024-11-12 06:50:40

使用这个:http://www.quirksmode.org/js/detect.html

alert(BrowserDetect.browser); // will say "Firefox"
alert(BrowserDetect.version); // will say "3" or "4"

Use this: http://www.quirksmode.org/js/detect.html

alert(BrowserDetect.browser); // will say "Firefox"
alert(BrowserDetect.version); // will say "3" or "4"
薄荷港 2024-11-12 06:50:40

我一直在为自己寻找解决方案,因为 jQuery 1.9.1 及更高版本已删除 $.browser 功能。我想出了这个对我有用的小功能。
它确实需要一个全局变量(我称之为我的_browser)来检查它是哪个浏览器。我编写了一个jsfiddle来说明如何使用它,当然,只需添加 _browser.foo 的测试即可将其扩展到其他浏览器,其中 foo 是浏览器的名称。我只做了流行的。

检测浏览器()

_browser = {};

function detectBrowser() {
  var uagent = navigator.userAgent.toLowerCase(),
      match = '';
    
  _browser.chrome  = /webkit/.test(uagent)  && /chrome/.test(uagent)      &&
                     !/edge/.test(uagent);

  _browser.firefox = /mozilla/.test(uagent) && /firefox/.test(uagent);

  _browser.msie    = /msie/.test(uagent)    || /trident/.test(uagent)     ||
                     /edge/.test(uagent);

  _browser.safari  = /safari/.test(uagent)  && /applewebkit/.test(uagent) &&
                     !/chrome/.test(uagent);

  _browser.opr     = /mozilla/.test(uagent) && /applewebkit/.test(uagent) &&
                     /chrome/.test(uagent)  && /safari/.test(uagent)      &&
                     /opr/.test(uagent);

  _browser.version = '';
    
  for (x in _browser) {
    if (_browser[x]) {

      match = uagent.match(
                new RegExp("(" + (x === "msie" ? "msie|edge" : x) + ")( |\/)([0-9]+)")
              );

      if (match) {
        _browser.version = match[3];
      } else {
        match = uagent.match(new RegExp("rv:([0-9]+)"));
        _browser.version = match ? match[1] : "";
      }
      break;
    }
  }
  _browser.opera = _browser.opr;
  delete _browser.opr;
}

detectBrowser();

console.log(_browser)

要检查当前浏览器是否是 Opera,您需要

if (_browser.opera) { // Opera specific code }

编辑修复格式,修复 IE11 和 Opera/Chrome 的检测,将结果更改为 browserResult。现在,_browser 键的顺序并不重要。更新了jsFiddle链接。

2015/08/11 编辑 为 Internet Explorer 12 (EDGE) 添加了新的测试用例,修复了一个小的正则表达式问题。更新了jsFiddle链接。

I was looking for a solution for myself, since jQuery 1.9.1 and above have removed the $.browser functionality. I came up with this little function that works for me.
It does need a global variable (I've called mine _browser) in order to check which browser it is. I've written a jsfiddle to illustrate how it can be used, of course it can be expanded for other browsers by just adding a test for _browser.foo, where foo is the name of the browser. I did just the popular ones.

detectBrowser()

_browser = {};

function detectBrowser() {
  var uagent = navigator.userAgent.toLowerCase(),
      match = '';
    
  _browser.chrome  = /webkit/.test(uagent)  && /chrome/.test(uagent)      &&
                     !/edge/.test(uagent);

  _browser.firefox = /mozilla/.test(uagent) && /firefox/.test(uagent);

  _browser.msie    = /msie/.test(uagent)    || /trident/.test(uagent)     ||
                     /edge/.test(uagent);

  _browser.safari  = /safari/.test(uagent)  && /applewebkit/.test(uagent) &&
                     !/chrome/.test(uagent);

  _browser.opr     = /mozilla/.test(uagent) && /applewebkit/.test(uagent) &&
                     /chrome/.test(uagent)  && /safari/.test(uagent)      &&
                     /opr/.test(uagent);

  _browser.version = '';
    
  for (x in _browser) {
    if (_browser[x]) {

      match = uagent.match(
                new RegExp("(" + (x === "msie" ? "msie|edge" : x) + ")( |\/)([0-9]+)")
              );

      if (match) {
        _browser.version = match[3];
      } else {
        match = uagent.match(new RegExp("rv:([0-9]+)"));
        _browser.version = match ? match[1] : "";
      }
      break;
    }
  }
  _browser.opera = _browser.opr;
  delete _browser.opr;
}

detectBrowser();

console.log(_browser)

To check if the current browser is Opera you would do

if (_browser.opera) { // Opera specific code }

Edit Fixed the formatting, fixed the detection for IE11 and Opera/Chrome, changed to browserResult from result. Now the order of the _browser keys doesn't matter. Updated jsFiddle link.

2015/08/11 Edit Added new testcase for Internet Explorer 12 (EDGE), fixed a small regexp problem. Updated jsFiddle link.

吻风 2024-11-12 06:50:40
function BrowserCheck()
{
    var N= navigator.appName, ua= navigator.userAgent, tem;
    var M= ua.match(/(opera|chrome|safari|firefox|msie|trident)\/?\s*(\.?\d+(\.\d+)*)/i);
    if(M && (tem= ua.match(/version\/([\.\d]+)/i))!= null) {M[2]=tem[1];}
    M= M? [M[1], M[2]]: [N, navigator.appVersion,'-?'];
    return M;
}

这将返回一个数组,第一个元素是浏览器名称,第二个元素是字符串格式的完整版本号。

function BrowserCheck()
{
    var N= navigator.appName, ua= navigator.userAgent, tem;
    var M= ua.match(/(opera|chrome|safari|firefox|msie|trident)\/?\s*(\.?\d+(\.\d+)*)/i);
    if(M && (tem= ua.match(/version\/([\.\d]+)/i))!= null) {M[2]=tem[1];}
    M= M? [M[1], M[2]]: [N, navigator.appVersion,'-?'];
    return M;
}

This will return an array, first element is the browser name, second element is the complete version number in string format.

挖个坑埋了你 2024-11-12 06:50:40

这是 Fzs2 和 Fzs2 的更新肯纳贝克新边缘铬

function get_browser() {
    var ua=navigator.userAgent,tem,M=ua.match(/(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i) || []; 
    if(/trident/i.test(M[1])){
        tem=/\brv[ :]+(\d+)/g.exec(ua) || []; 
        return {name:'IE',version:(tem[1]||'')};
        }   
    if(M[1]==='Chrome'){
        tem=ua.match(/\bEdg\/(\d+)/)
        if(tem!=null)   {return {name:'Edge(Chromium)', version:tem[1]};}
        tem=ua.match(/\bOPR\/(\d+)/)
        if(tem!=null)   {return {name:'Opera', version:tem[1]};}
        }   
    M=M[2]? [M[1], M[2]]: [navigator.appName, navigator.appVersion, '-?'];
    if((tem=ua.match(/version\/(\d+)/i))!=null) {M.splice(1,1,tem[1]);}
    return {
      name: M[0],
      version: M[1]
    };
 }

var browser=get_browser(); // browser.name = 'Edge(Chromium)'
                           // browser.version = '86'

console.log(browser);

This is a Update on Fzs2 & kennebec For New Edge Chromium

function get_browser() {
    var ua=navigator.userAgent,tem,M=ua.match(/(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i) || []; 
    if(/trident/i.test(M[1])){
        tem=/\brv[ :]+(\d+)/g.exec(ua) || []; 
        return {name:'IE',version:(tem[1]||'')};
        }   
    if(M[1]==='Chrome'){
        tem=ua.match(/\bEdg\/(\d+)/)
        if(tem!=null)   {return {name:'Edge(Chromium)', version:tem[1]};}
        tem=ua.match(/\bOPR\/(\d+)/)
        if(tem!=null)   {return {name:'Opera', version:tem[1]};}
        }   
    M=M[2]? [M[1], M[2]]: [navigator.appName, navigator.appVersion, '-?'];
    if((tem=ua.match(/version\/(\d+)/i))!=null) {M.splice(1,1,tem[1]);}
    return {
      name: M[0],
      version: M[1]
    };
 }

var browser=get_browser(); // browser.name = 'Edge(Chromium)'
                           // browser.version = '86'

console.log(browser);

ㄟ。诗瑗 2024-11-12 06:50:40

在纯 Javascript 中,您可以在 navigator.userAgent 上进行正则表达式匹配来查找 Firefox 版本:

var uMatch = navigator.userAgent.match(/Firefox\/(.*)$/),
    ffVersion;
if (uMatch && uMatch.length > 1) {
    ffVersion = uMatch[1];
}

如果不是 Firefox 浏览器,ffVersion 将为 undefined

查看工作示例→

In pure Javascript you can do a RegExp match on the navigator.userAgent to find the Firefox version:

var uMatch = navigator.userAgent.match(/Firefox\/(.*)$/),
    ffVersion;
if (uMatch && uMatch.length > 1) {
    ffVersion = uMatch[1];
}

ffVersion will be undefined if not a Firefox browser.

See working example →

别理我 2024-11-12 06:50:40

jQuery 可以很好地处理这个问题 (jQuery.browser)

var ua = $.browser;
if ( ua.mozilla && ua.version.slice(0,3) == "1.9" ) {
    alert( "Do stuff for firefox 3" );
}

编辑:正如 Joshua 在下面的评论中所写,自版本 1.9 以来,jQuery 不再支持 jQuery.browser 属性(请阅读 jQuery 1.9 发行说明 了解更多详情)。
jQuery 开发团队
建议使用更完整的方法,例如使用 Modernizr 库。

jQuery can handle this quite nice (jQuery.browser)

var ua = $.browser;
if ( ua.mozilla && ua.version.slice(0,3) == "1.9" ) {
    alert( "Do stuff for firefox 3" );
}

EDIT: As Joshua wrote in his comment below, jQuery.browser property is no longer supported in jQuery since version 1.9 (read jQuery 1.9 release notes for more details).
jQuery development team recommends using more complete approach like adapting UI with Modernizr library.

不交电费瞎发啥光 2024-11-12 06:50:40

检测浏览器及其版本

此代码段基于 MDN。他们给出了有关可用于检测浏览器名称的各种关键字的简短提示。

reference

我做了一些更改来检测 EdgeUCBrowser 等浏览器

getBrowser = () => {
    const userAgent = navigator.userAgent;
    let browser = "unkown";
    // Detect browser name
    browser = (/ucbrowser/i).test(userAgent) ? 'UCBrowser' : browser;
    browser = (/edg/i).test(userAgent) ? 'Edge' : browser;
    browser = (/googlebot/i).test(userAgent) ? 'GoogleBot' : browser;
    browser = (/chromium/i).test(userAgent) ? 'Chromium' : browser;
    browser = (/firefox|fxios/i).test(userAgent) && !(/seamonkey/i).test(userAgent) ? 'Firefox' : browser;
    browser = (/; msie|trident/i).test(userAgent) && !(/ucbrowser/i).test(userAgent) ? 'IE' : browser;
    browser = (/chrome|crios/i).test(userAgent) && !(/opr|opera|chromium|edg|ucbrowser|googlebot/i).test(userAgent) ? 'Chrome' : browser;;
    browser = (/safari/i).test(userAgent) && !(/chromium|edg|ucbrowser|chrome|crios|opr|opera|fxios|firefox/i).test(userAgent) ? 'Safari' : browser;
    browser = (/opr|opera/i).test(userAgent) ? 'Opera' : browser;

    // detect browser version
    switch (browser) {
        case 'UCBrowser': return `${browser}/${browserVersion(userAgent,/(ucbrowser)\/([\d\.]+)/i)}`;
        case 'Edge': return `${browser}/${browserVersion(userAgent,/(edge|edga|edgios|edg)\/([\d\.]+)/i)}`;
        case 'GoogleBot': return `${browser}/${browserVersion(userAgent,/(googlebot)\/([\d\.]+)/i)}`;
        case 'Chromium': return `${browser}/${browserVersion(userAgent,/(chromium)\/([\d\.]+)/i)}`;
        case 'Firefox': return `${browser}/${browserVersion(userAgent,/(firefox|fxios)\/([\d\.]+)/i)}`;
        case 'Chrome': return `${browser}/${browserVersion(userAgent,/(chrome|crios)\/([\d\.]+)/i)}`;
        case 'Safari': return `${browser}/${browserVersion(userAgent,/(safari)\/([\d\.]+)/i)}`;
        case 'Opera': return `${browser}/${browserVersion(userAgent,/(opera|opr)\/([\d\.]+)/i)}`;
        case 'IE': const version = browserVersion(userAgent,/(trident)\/([\d\.]+)/i);
            // IE version is mapped using trident version 
            // IE/8.0 = Trident/4.0, IE/9.0 = Trident/5.0
            return version ? `${browser}/${parseFloat(version) + 4.0}` : `${browser}/7.0`;
        default: return `unknown/0.0.0.0`;
    }
}

browserVersion = (userAgent,regex) => {
    return userAgent.match(regex) ? userAgent.match(regex)[2] : null;
}

console.log(getBrowser());

Detecting Browser and Its version

This code snippet is based on the article from MDN. Where they gave a brief hint about various keywords that can be used to detect the browser name.

reference

I have done few changes to detect browsers like Edge and UCBrowser

getBrowser = () => {
    const userAgent = navigator.userAgent;
    let browser = "unkown";
    // Detect browser name
    browser = (/ucbrowser/i).test(userAgent) ? 'UCBrowser' : browser;
    browser = (/edg/i).test(userAgent) ? 'Edge' : browser;
    browser = (/googlebot/i).test(userAgent) ? 'GoogleBot' : browser;
    browser = (/chromium/i).test(userAgent) ? 'Chromium' : browser;
    browser = (/firefox|fxios/i).test(userAgent) && !(/seamonkey/i).test(userAgent) ? 'Firefox' : browser;
    browser = (/; msie|trident/i).test(userAgent) && !(/ucbrowser/i).test(userAgent) ? 'IE' : browser;
    browser = (/chrome|crios/i).test(userAgent) && !(/opr|opera|chromium|edg|ucbrowser|googlebot/i).test(userAgent) ? 'Chrome' : browser;;
    browser = (/safari/i).test(userAgent) && !(/chromium|edg|ucbrowser|chrome|crios|opr|opera|fxios|firefox/i).test(userAgent) ? 'Safari' : browser;
    browser = (/opr|opera/i).test(userAgent) ? 'Opera' : browser;

    // detect browser version
    switch (browser) {
        case 'UCBrowser': return `${browser}/${browserVersion(userAgent,/(ucbrowser)\/([\d\.]+)/i)}`;
        case 'Edge': return `${browser}/${browserVersion(userAgent,/(edge|edga|edgios|edg)\/([\d\.]+)/i)}`;
        case 'GoogleBot': return `${browser}/${browserVersion(userAgent,/(googlebot)\/([\d\.]+)/i)}`;
        case 'Chromium': return `${browser}/${browserVersion(userAgent,/(chromium)\/([\d\.]+)/i)}`;
        case 'Firefox': return `${browser}/${browserVersion(userAgent,/(firefox|fxios)\/([\d\.]+)/i)}`;
        case 'Chrome': return `${browser}/${browserVersion(userAgent,/(chrome|crios)\/([\d\.]+)/i)}`;
        case 'Safari': return `${browser}/${browserVersion(userAgent,/(safari)\/([\d\.]+)/i)}`;
        case 'Opera': return `${browser}/${browserVersion(userAgent,/(opera|opr)\/([\d\.]+)/i)}`;
        case 'IE': const version = browserVersion(userAgent,/(trident)\/([\d\.]+)/i);
            // IE version is mapped using trident version 
            // IE/8.0 = Trident/4.0, IE/9.0 = Trident/5.0
            return version ? `${browser}/${parseFloat(version) + 4.0}` : `${browser}/7.0`;
        default: return `unknown/0.0.0.0`;
    }
}

browserVersion = (userAgent,regex) => {
    return userAgent.match(regex) ? userAgent.match(regex)[2] : null;
}

console.log(getBrowser());

屌丝范 2024-11-12 06:50:40

查看 navigator.userAgent - Firefox/xxx.xxx.xxx 在最后指定。

Look at navigator.userAgent - Firefox/xxx.xxx.xxx is specified right at the end.

或十年 2024-11-12 06:50:40

我根据 Hermann Ingjaldsson 的答案编写了一个版本检测器,但更强大,并且返回一个包含名称/版本数据的对象。它涵盖了主要的浏览器,但我不关心过多的移动浏览器和次要浏览器:

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

然后可以像这样使用它:

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

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.
清浅ˋ旧时光 2024-11-12 06:50:40

为此,您需要检查 navigator.appVersion 或 navigator.userAgent 的值
尝试使用:

console.log(navigator.appVersion)

For this you need to check the value of navigator.appVersion or navigator.userAgent
Try using:

console.log(navigator.appVersion)
夜还是长夜 2024-11-12 06:50:40
<script type="text/javascript">
var version = navigator.appVersion;
alert(version);
</script>
<script type="text/javascript">
var version = navigator.appVersion;
alert(version);
</script>
一袭白衣梦中忆 2024-11-12 06:50:40
var nVer = navigator.appVersion;
var nAgt = navigator.userAgent;
var browserName  = navigator.appName;
var fullVersion  = ''+parseFloat(navigator.appVersion);
var majorVersion = parseInt(navigator.appVersion,10);
var nameOffset,verOffset,ix;

// In Opera, the true version is after "Opera" or after "Version"

if ((verOffset=nAgt.indexOf("Opera"))!=-1) {
 browserName = "Opera";
 fullVersion = nAgt.substring(verOffset+6);
 if ((verOffset=nAgt.indexOf("Version"))!=-1)
   fullVersion = nAgt.substring(verOffset+8);
}
// In MSIE, the true version is after "MSIE" in userAgent

else if ((verOffset=nAgt.indexOf("MSIE"))!=-1) {
 browserName = "Microsoft Internet Explorer";
 fullVersion = nAgt.substring(verOffset+5);
}
// In Chrome, the true version is after "Chrome"

else if ((verOffset=nAgt.indexOf("Chrome"))!=-1) {
 browserName = "Chrome";
 fullVersion = nAgt.substring(verOffset+7);
}
// In Safari, the true version is after "Safari" or after "Version"

else if ((verOffset=nAgt.indexOf("Safari"))!=-1) {
 browserName = "Safari";
 fullVersion = nAgt.substring(verOffset+7);
 if ((verOffset=nAgt.indexOf("Version"))!=-1)
   fullVersion = nAgt.substring(verOffset+8);
}
// In Firefox, the true version is after "Firefox"

else if ((verOffset=nAgt.indexOf("Firefox"))!=-1) {
 browserName = "Firefox";
 fullVersion = nAgt.substring(verOffset+8);
}
// In most other browsers, "name/version" is at the end of userAgent

else if ( (nameOffset=nAgt.lastIndexOf(' ')+1) <
          (verOffset=nAgt.lastIndexOf('/')) )
{
 browserName = nAgt.substring(nameOffset,verOffset);
 fullVersion = nAgt.substring(verOffset+1);
 if (browserName.toLowerCase()==browserName.toUpperCase()) {
  browserName = navigator.appName;
 }
}

// trim the fullVersion string at semicolon/space if present

if ((ix=fullVersion.indexOf(";"))!=-1)
   fullVersion=fullVersion.substring(0,ix);
if ((ix=fullVersion.indexOf(" "))!=-1)
   fullVersion=fullVersion.substring(0,ix);

majorVersion = parseInt(''+fullVersion,10);
if (isNaN(majorVersion)) {
 fullVersion  = ''+parseFloat(navigator.appVersion);
 majorVersion = parseInt(navigator.appVersion,10);
}

document.write(''
 +'Browser name  = '+browserName+'<br>'
 +'Full version  = '+fullVersion+'<br>'
 +'Major version = '+majorVersion+'<br>'
 +'navigator.appName = '+navigator.appName+'<br>'
 +'navigator.userAgent = '+navigator.userAgent+'<br>'
)

请在此处查看演示..http://jsfiddle.net/hw4jM/3/

var nVer = navigator.appVersion;
var nAgt = navigator.userAgent;
var browserName  = navigator.appName;
var fullVersion  = ''+parseFloat(navigator.appVersion);
var majorVersion = parseInt(navigator.appVersion,10);
var nameOffset,verOffset,ix;

// In Opera, the true version is after "Opera" or after "Version"

if ((verOffset=nAgt.indexOf("Opera"))!=-1) {
 browserName = "Opera";
 fullVersion = nAgt.substring(verOffset+6);
 if ((verOffset=nAgt.indexOf("Version"))!=-1)
   fullVersion = nAgt.substring(verOffset+8);
}
// In MSIE, the true version is after "MSIE" in userAgent

else if ((verOffset=nAgt.indexOf("MSIE"))!=-1) {
 browserName = "Microsoft Internet Explorer";
 fullVersion = nAgt.substring(verOffset+5);
}
// In Chrome, the true version is after "Chrome"

else if ((verOffset=nAgt.indexOf("Chrome"))!=-1) {
 browserName = "Chrome";
 fullVersion = nAgt.substring(verOffset+7);
}
// In Safari, the true version is after "Safari" or after "Version"

else if ((verOffset=nAgt.indexOf("Safari"))!=-1) {
 browserName = "Safari";
 fullVersion = nAgt.substring(verOffset+7);
 if ((verOffset=nAgt.indexOf("Version"))!=-1)
   fullVersion = nAgt.substring(verOffset+8);
}
// In Firefox, the true version is after "Firefox"

else if ((verOffset=nAgt.indexOf("Firefox"))!=-1) {
 browserName = "Firefox";
 fullVersion = nAgt.substring(verOffset+8);
}
// In most other browsers, "name/version" is at the end of userAgent

else if ( (nameOffset=nAgt.lastIndexOf(' ')+1) <
          (verOffset=nAgt.lastIndexOf('/')) )
{
 browserName = nAgt.substring(nameOffset,verOffset);
 fullVersion = nAgt.substring(verOffset+1);
 if (browserName.toLowerCase()==browserName.toUpperCase()) {
  browserName = navigator.appName;
 }
}

// trim the fullVersion string at semicolon/space if present

if ((ix=fullVersion.indexOf(";"))!=-1)
   fullVersion=fullVersion.substring(0,ix);
if ((ix=fullVersion.indexOf(" "))!=-1)
   fullVersion=fullVersion.substring(0,ix);

majorVersion = parseInt(''+fullVersion,10);
if (isNaN(majorVersion)) {
 fullVersion  = ''+parseFloat(navigator.appVersion);
 majorVersion = parseInt(navigator.appVersion,10);
}

document.write(''
 +'Browser name  = '+browserName+'<br>'
 +'Full version  = '+fullVersion+'<br>'
 +'Major version = '+majorVersion+'<br>'
 +'navigator.appName = '+navigator.appName+'<br>'
 +'navigator.userAgent = '+navigator.userAgent+'<br>'
)

See the demo here..http://jsfiddle.net/hw4jM/3/

白馒头 2024-11-12 06:50:40

我用 ASP 代码编写了一个脚本来检测浏览器、浏览器版本、操作系统和操作系统版本。
我在 ASP 中执行此操作的原因是因为我想将数据存储在日志数据库中。
所以我必须检测浏览器服务器端。

这是代码:

on error resume next
ua = lcase(Request.ServerVariables("HTTP_USER_AGENT"))
moz = instr(ua,"mozilla")  
ffx = instr(ua,"firefox")  
saf = instr(ua,"safari")
crm = instr(ua,"chrome") 
max = instr(ua,"maxthon") 
opr = instr(ua,"opera")
ie4 = instr(ua,"msie 4") 
ie5 = instr(ua,"msie 5") 
ie6 = instr(ua,"msie 6") 
ie7 = instr(ua,"msie 7") 
ie8 = instr(ua,"trident/4.0")
ie9 = instr(ua,"trident/5.0")

if moz>0 then 
    BrowserType = "Mozilla"
    BrVer = mid(ua,moz+8,(instr(moz,ua," ")-(moz+8)))
end if
if ffx>0 then 
    BrowserType = "FireFox"
    BrVer = mid(ua,ffx+8)
end if
if saf>0 then 
    BrowserType = "Safari"
    BrVerPlass = instr(ua,"version")
    BrVer = mid(ua,BrVerPlass+8,(instr(BrVerPlass,ua," ")-(BrVerPlass+8)))
end if
if crm>0 then 
    BrowserType = "Chrome"
    BrVer = mid(ua,crm+7,(instr(crm,ua," ")-(crm+7)))
end if
if max>0 then 
    BrowserType = "Maxthon"
    BrVer = mid(ua,max+8,(instr(max,ua," ")-(max+8)))
end if
if opr>0 then 
    BrowserType = "Opera"
    BrVerPlass = instr(ua,"presto")
    BrVer = mid(ua,BrVerPlass+7,(instr(BrVerPlass,ua," ")-(BrVerPlass+7)))
end if
if ie4>0 then 
    BrowserType = "Internet Explorer"
    BrVer = "4"
end if
if ie5>0 then 
    BrowserType = "Internet Explorer"
    BrVer = "5"
end if
if ie6>0 then 
    BrowserType = "Internet Explorer"
    BrVer = "6"
end if
if ie7>0 then 
    BrowserType = "Internet Explorer"
    BrVer = "7"
end if
if ie8>0 then 
    BrowserType = "Internet Explorer"
    BrVer = "8"
    if ie7>0 then BrVer = BrVer & " (in IE7 compability mode)"
end if
if ie9>0 then 
    BrowserType = "Internet Explorer"
    BrVer = "9"
    if ie7>0 then BrVer = BrVer & " (in IE7 compability mode)"
    if ie8>0 then BrVer = BrVer & " (in IE8 compability mode)"
end if

OSSel = mid(ua,instr(ua,"(")+1,(instr(ua,";")-instr(ua,"("))-1)
OSver = mid(ua,instr(ua,";")+1,(instr(ua,")")-instr(ua,";"))-1)

if BrowserType = "Internet Explorer" then
    OSStart = instr(ua,";")
    OSStart = instr(OSStart+1,ua,";")        
    OSStopp = instr(OSStart+1,ua,";")
    OSsel = mid(ua,OSStart+2,(OSStopp-OSStart)-2)
end if

    Select case OSsel
        case "windows nt 6.1"
            OS = "Windows"
            OSver = "7"
        case "windows nt 6.0"
            OS = "Windows"
            OSver = "Vista"
        case "windows nt 5.2"
            OS = "Windows"
            OSver = "Srv 2003 / XP x64"
        case "windows nt 5.1"
            OS = "Windows"
            OSver = "XP"
        case else
            OS = OSSel
    End select

Response.write "<br>" & ua & "<br>" & BrowserType & "<br>" & BrVer & "<br>" & OS & "<br>" & OSver & "<br>"

'Use the variables here for whatever you need........

I have made a script in ASP code to detect browser, browser version, OS and OS version.
The reason for me to do this in ASP was because i want to store the data in a log-database.
So I had to detect the browser serverside.

Here is the code:

on error resume next
ua = lcase(Request.ServerVariables("HTTP_USER_AGENT"))
moz = instr(ua,"mozilla")  
ffx = instr(ua,"firefox")  
saf = instr(ua,"safari")
crm = instr(ua,"chrome") 
max = instr(ua,"maxthon") 
opr = instr(ua,"opera")
ie4 = instr(ua,"msie 4") 
ie5 = instr(ua,"msie 5") 
ie6 = instr(ua,"msie 6") 
ie7 = instr(ua,"msie 7") 
ie8 = instr(ua,"trident/4.0")
ie9 = instr(ua,"trident/5.0")

if moz>0 then 
    BrowserType = "Mozilla"
    BrVer = mid(ua,moz+8,(instr(moz,ua," ")-(moz+8)))
end if
if ffx>0 then 
    BrowserType = "FireFox"
    BrVer = mid(ua,ffx+8)
end if
if saf>0 then 
    BrowserType = "Safari"
    BrVerPlass = instr(ua,"version")
    BrVer = mid(ua,BrVerPlass+8,(instr(BrVerPlass,ua," ")-(BrVerPlass+8)))
end if
if crm>0 then 
    BrowserType = "Chrome"
    BrVer = mid(ua,crm+7,(instr(crm,ua," ")-(crm+7)))
end if
if max>0 then 
    BrowserType = "Maxthon"
    BrVer = mid(ua,max+8,(instr(max,ua," ")-(max+8)))
end if
if opr>0 then 
    BrowserType = "Opera"
    BrVerPlass = instr(ua,"presto")
    BrVer = mid(ua,BrVerPlass+7,(instr(BrVerPlass,ua," ")-(BrVerPlass+7)))
end if
if ie4>0 then 
    BrowserType = "Internet Explorer"
    BrVer = "4"
end if
if ie5>0 then 
    BrowserType = "Internet Explorer"
    BrVer = "5"
end if
if ie6>0 then 
    BrowserType = "Internet Explorer"
    BrVer = "6"
end if
if ie7>0 then 
    BrowserType = "Internet Explorer"
    BrVer = "7"
end if
if ie8>0 then 
    BrowserType = "Internet Explorer"
    BrVer = "8"
    if ie7>0 then BrVer = BrVer & " (in IE7 compability mode)"
end if
if ie9>0 then 
    BrowserType = "Internet Explorer"
    BrVer = "9"
    if ie7>0 then BrVer = BrVer & " (in IE7 compability mode)"
    if ie8>0 then BrVer = BrVer & " (in IE8 compability mode)"
end if

OSSel = mid(ua,instr(ua,"(")+1,(instr(ua,";")-instr(ua,"("))-1)
OSver = mid(ua,instr(ua,";")+1,(instr(ua,")")-instr(ua,";"))-1)

if BrowserType = "Internet Explorer" then
    OSStart = instr(ua,";")
    OSStart = instr(OSStart+1,ua,";")        
    OSStopp = instr(OSStart+1,ua,";")
    OSsel = mid(ua,OSStart+2,(OSStopp-OSStart)-2)
end if

    Select case OSsel
        case "windows nt 6.1"
            OS = "Windows"
            OSver = "7"
        case "windows nt 6.0"
            OS = "Windows"
            OSver = "Vista"
        case "windows nt 5.2"
            OS = "Windows"
            OSver = "Srv 2003 / XP x64"
        case "windows nt 5.1"
            OS = "Windows"
            OSver = "XP"
        case else
            OS = OSSel
    End select

Response.write "<br>" & ua & "<br>" & BrowserType & "<br>" & BrVer & "<br>" & OS & "<br>" & OSver & "<br>"

'Use the variables here for whatever you need........
故事与诗 2024-11-12 06:50:40

此页面似乎有一个非常好的代码片段,仅使用 appString 和 appVersion 属性作为最后的手段,因为它声称它们对某些浏览器不可靠。
页面代码如下:

var nVer = navigator.appVersion;
var nAgt = navigator.userAgent;
var browserName  = navigator.appName;
var fullVersion  = ''+parseFloat(navigator.appVersion); 
var majorVersion = parseInt(navigator.appVersion,10);
var nameOffset,verOffset,ix;

// In Opera 15+, the true version is after "OPR/" 
if ((verOffset=nAgt.indexOf("OPR/"))!=-1) {
 browserName = "Opera";
 fullVersion = nAgt.substring(verOffset+4);
}
// In older Opera, the true version is after "Opera" or after "Version"
else if ((verOffset=nAgt.indexOf("Opera"))!=-1) {
 browserName = "Opera";
 fullVersion = nAgt.substring(verOffset+6);
 if ((verOffset=nAgt.indexOf("Version"))!=-1) 
   fullVersion = nAgt.substring(verOffset+8);
}
// In MSIE, the true version is after "MSIE" in userAgent
else if ((verOffset=nAgt.indexOf("MSIE"))!=-1) {
 browserName = "Microsoft Internet Explorer";
 fullVersion = nAgt.substring(verOffset+5);
}
// In Chrome, the true version is after "Chrome" 
else if ((verOffset=nAgt.indexOf("Chrome"))!=-1) {
 browserName = "Chrome";
 fullVersion = nAgt.substring(verOffset+7);
}
// In Safari, the true version is after "Safari" or after "Version" 
else if ((verOffset=nAgt.indexOf("Safari"))!=-1) {
 browserName = "Safari";
 fullVersion = nAgt.substring(verOffset+7);
 if ((verOffset=nAgt.indexOf("Version"))!=-1) 
   fullVersion = nAgt.substring(verOffset+8);
}
// In Firefox, the true version is after "Firefox" 
else if ((verOffset=nAgt.indexOf("Firefox"))!=-1) {
 browserName = "Firefox";
 fullVersion = nAgt.substring(verOffset+8);
}
// In most other browsers, "name/version" is at the end of userAgent 
else if ( (nameOffset=nAgt.lastIndexOf(' ')+1) < 
          (verOffset=nAgt.lastIndexOf('/')) ) 
{
 browserName = nAgt.substring(nameOffset,verOffset);
 fullVersion = nAgt.substring(verOffset+1);
 if (browserName.toLowerCase()==browserName.toUpperCase()) {
  browserName = navigator.appName;
 }
}
// trim the fullVersion string at semicolon/space if present
if ((ix=fullVersion.indexOf(";"))!=-1)
   fullVersion=fullVersion.substring(0,ix);
if ((ix=fullVersion.indexOf(" "))!=-1)
   fullVersion=fullVersion.substring(0,ix);

majorVersion = parseInt(''+fullVersion,10);
if (isNaN(majorVersion)) {
 fullVersion  = ''+parseFloat(navigator.appVersion); 
 majorVersion = parseInt(navigator.appVersion,10);
}

document.write(''
 +'Browser name  = '+browserName+'<br>'
 +'Full version  = '+fullVersion+'<br>'
 +'Major version = '+majorVersion+'<br>'
 +'navigator.appName = '+navigator.appName+'<br>'
 +'navigator.userAgent = '+navigator.userAgent+'<br>'
)

This page seems to have a pretty nice snippet which only uses the appString and appVersion property as a last resort as it claims them to be unreliable with certain browsers.
The code on the page is as follows:

var nVer = navigator.appVersion;
var nAgt = navigator.userAgent;
var browserName  = navigator.appName;
var fullVersion  = ''+parseFloat(navigator.appVersion); 
var majorVersion = parseInt(navigator.appVersion,10);
var nameOffset,verOffset,ix;

// In Opera 15+, the true version is after "OPR/" 
if ((verOffset=nAgt.indexOf("OPR/"))!=-1) {
 browserName = "Opera";
 fullVersion = nAgt.substring(verOffset+4);
}
// In older Opera, the true version is after "Opera" or after "Version"
else if ((verOffset=nAgt.indexOf("Opera"))!=-1) {
 browserName = "Opera";
 fullVersion = nAgt.substring(verOffset+6);
 if ((verOffset=nAgt.indexOf("Version"))!=-1) 
   fullVersion = nAgt.substring(verOffset+8);
}
// In MSIE, the true version is after "MSIE" in userAgent
else if ((verOffset=nAgt.indexOf("MSIE"))!=-1) {
 browserName = "Microsoft Internet Explorer";
 fullVersion = nAgt.substring(verOffset+5);
}
// In Chrome, the true version is after "Chrome" 
else if ((verOffset=nAgt.indexOf("Chrome"))!=-1) {
 browserName = "Chrome";
 fullVersion = nAgt.substring(verOffset+7);
}
// In Safari, the true version is after "Safari" or after "Version" 
else if ((verOffset=nAgt.indexOf("Safari"))!=-1) {
 browserName = "Safari";
 fullVersion = nAgt.substring(verOffset+7);
 if ((verOffset=nAgt.indexOf("Version"))!=-1) 
   fullVersion = nAgt.substring(verOffset+8);
}
// In Firefox, the true version is after "Firefox" 
else if ((verOffset=nAgt.indexOf("Firefox"))!=-1) {
 browserName = "Firefox";
 fullVersion = nAgt.substring(verOffset+8);
}
// In most other browsers, "name/version" is at the end of userAgent 
else if ( (nameOffset=nAgt.lastIndexOf(' ')+1) < 
          (verOffset=nAgt.lastIndexOf('/')) ) 
{
 browserName = nAgt.substring(nameOffset,verOffset);
 fullVersion = nAgt.substring(verOffset+1);
 if (browserName.toLowerCase()==browserName.toUpperCase()) {
  browserName = navigator.appName;
 }
}
// trim the fullVersion string at semicolon/space if present
if ((ix=fullVersion.indexOf(";"))!=-1)
   fullVersion=fullVersion.substring(0,ix);
if ((ix=fullVersion.indexOf(" "))!=-1)
   fullVersion=fullVersion.substring(0,ix);

majorVersion = parseInt(''+fullVersion,10);
if (isNaN(majorVersion)) {
 fullVersion  = ''+parseFloat(navigator.appVersion); 
 majorVersion = parseInt(navigator.appVersion,10);
}

document.write(''
 +'Browser name  = '+browserName+'<br>'
 +'Full version  = '+fullVersion+'<br>'
 +'Major version = '+majorVersion+'<br>'
 +'navigator.appName = '+navigator.appName+'<br>'
 +'navigator.userAgent = '+navigator.userAgent+'<br>'
)
黄昏下泛黄的笔记 2024-11-12 06:50:40

添加我自己对赫尔曼答案的实现。我需要操作系统检测,因此已添加。还包括一些您可能需要进行 ES5 化的 ES6 代码(因为我们有一个转译器)。

detectClient() {
    let nav = navigator.appVersion,
        os = 'unknown',
        client = (() => {
            let agent = navigator.userAgent,
                engine = agent.match(/(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i) || [],
                build;

            if(/trident/i.test(engine[1])){
                build = /\brv[ :]+(\d+)/g.exec(agent) || [];
                return {browser:'IE', version:(build[1] || '')};
            }

            if(engine[1] === 'Chrome'){
                build = agent.match(/\bOPR\/(\d+)/);

                if(build !== null) {
                    return {browser: 'Opera', version: build[1]};
                }
            }

            engine = engine[2] ? [engine[1], engine[2]] : [navigator.appName, nav, '-?'];

            if((build = agent.match(/version\/(\d+)/i)) !== null) {
                engine.splice(1, 1, build[1]);
            }

            return {
              browser: engine[0],
              version: engine[1]
            };
        })();

    switch (true) {
        case nav.indexOf('Win') > -1:
            os = 'Windows';
        break;
        case nav.indexOf('Mac') > -1:
            os = 'MacOS';
        break;
        case nav.indexOf('X11') > -1:
            os = 'UNIX';
        break;
        case nav.indexOf('Linux') > -1:
            os = 'Linux';
        break;
    }        

    client.os = os;
    return client;
}

返回:对象{浏览器:“Chrome”,版本:“50”,操作系统:“UNIX”}

Adding my own implementation of Hermann's answer. I needed OS detection so that's been added. Also includes some ES6 code (because we have a transpiler) that you might need to ES5-ify.

detectClient() {
    let nav = navigator.appVersion,
        os = 'unknown',
        client = (() => {
            let agent = navigator.userAgent,
                engine = agent.match(/(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i) || [],
                build;

            if(/trident/i.test(engine[1])){
                build = /\brv[ :]+(\d+)/g.exec(agent) || [];
                return {browser:'IE', version:(build[1] || '')};
            }

            if(engine[1] === 'Chrome'){
                build = agent.match(/\bOPR\/(\d+)/);

                if(build !== null) {
                    return {browser: 'Opera', version: build[1]};
                }
            }

            engine = engine[2] ? [engine[1], engine[2]] : [navigator.appName, nav, '-?'];

            if((build = agent.match(/version\/(\d+)/i)) !== null) {
                engine.splice(1, 1, build[1]);
            }

            return {
              browser: engine[0],
              version: engine[1]
            };
        })();

    switch (true) {
        case nav.indexOf('Win') > -1:
            os = 'Windows';
        break;
        case nav.indexOf('Mac') > -1:
            os = 'MacOS';
        break;
        case nav.indexOf('X11') > -1:
            os = 'UNIX';
        break;
        case nav.indexOf('Linux') > -1:
            os = 'Linux';
        break;
    }        

    client.os = os;
    return client;
}

Returns: Object {browser: "Chrome", version: "50", os: "UNIX"}

-黛色若梦 2024-11-12 06:50:40

在这里,这比 @kennebec 片段具有更好的兼容性;
将返回浏览器名称和版本(返回 72 而不是 72.0.3626.96)。

在 Safari、Chrome、Opera、Firefox、IE、Edge、UCBrowser 以及移动设备上进行了测试。

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

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;
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文