230

如何使用 JavaScript 确定确切的浏览器和版本?

4

25 回答 25

371

navigator.saysWho = (() => {
  const { userAgent } = navigator
  let match = userAgent.match(/(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i) || []
  let temp

  if (/trident/i.test(match[1])) {
    temp = /\brv[ :]+(\d+)/g.exec(userAgent) || []

    return `IE ${temp[1] || ''}`
  }

  if (match[1] === 'Chrome') {
    temp = userAgent.match(/\b(OPR|Edge)\/(\d+)/)

    if (temp !== null) {
      return temp.slice(1).join(' ').replace('OPR', 'Opera')
    }

    temp = userAgent.match(/\b(Edg)\/(\d+)/)

    if (temp !== null) {
      return temp.slice(1).join(' ').replace('Edg', 'Edge (Chromium)')
    }
  }

  match = match[2] ? [ match[1], match[2] ] : [ navigator.appName, navigator.appVersion, '-?' ]
  temp = userAgent.match(/version\/(\d+)/i)

  if (temp !== null) {
    match.splice(1, 1, temp[1])
  }

  return match.join(' ')
})()

console.log(navigator.saysWho) // outputs: `Chrome 89`

顾名思义,这将告诉您浏览器提供的名称和版本号。

当您在多个浏览器上测试新代码时,它可以方便地对测试和错误结果进行排序。

于 2010-03-08T14:15:43.260 回答
70

我建议使用小型 JavaScript 库 Bowser。它基于navigator.userAgent所有浏览器(包括 iphone、android 等)并经过很好的测试。

https://github.com/ded/bowser

你可以简单地说:

if (bowser.msie && bowser.version <= 6) {
  alert('Hello IE');
} else if (bowser.firefox){
  alert('Hello Foxy');
} else if (bowser.chrome){
  alert('Hello Chrome');
} else if (bowser.safari){
  alert('Hello Safari');
} else if(bowser.iphone || bowser.android){
  alert('Hello mobile');
}
于 2013-02-13T20:05:35.233 回答
33

这是我为获取客户信息而写的

var ua = navigator.userAgent.toLowerCase();
var check = function(r) {
    return r.test(ua);
};
var DOC = document;
var isStrict = DOC.compatMode == "CSS1Compat";
var isOpera = check(/opera/);
var isChrome = check(/chrome/);
var isWebKit = check(/webkit/);
var isSafari = !isChrome && check(/safari/);
var isSafari2 = isSafari && check(/applewebkit\/4/); // unique to
// Safari 2
var isSafari3 = isSafari && check(/version\/3/);
var isSafari4 = isSafari && check(/version\/4/);
var isIE = !isOpera && check(/msie/);
var isIE7 = isIE && check(/msie 7/);
var isIE8 = isIE && check(/msie 8/);
var isIE6 = isIE && !isIE7 && !isIE8;
var isGecko = !isWebKit && check(/gecko/);
var isGecko2 = isGecko && check(/rv:1\.8/);
var isGecko3 = isGecko && check(/rv:1\.9/);
var isBorderBox = isIE && !isStrict;
var isWindows = check(/windows|win32/);
var isMac = check(/macintosh|mac os x/);
var isAir = check(/adobeair/);
var isLinux = check(/linux/);
var isSecure = /^https/i.test(window.location.protocol);
var isIE7InIE8 = isIE7 && DOC.documentMode == 7;

var jsType = '', browserType = '', browserVersion = '', osName = '';
var ua = navigator.userAgent.toLowerCase();
var check = function(r) {
    return r.test(ua);
};

if(isWindows){
    osName = 'Windows';

    if(check(/windows nt/)){
        var start = ua.indexOf('windows nt');
        var end = ua.indexOf(';', start);
        osName = ua.substring(start, end);
    }
} else {
    osName = isMac ? 'Mac' : isLinux ? 'Linux' : 'Other';
} 

if(isIE){
    browserType = 'IE';
    jsType = 'IE';

    var versionStart = ua.indexOf('msie') + 5;
    var versionEnd = ua.indexOf(';', versionStart);
    browserVersion = ua.substring(versionStart, versionEnd);

    jsType = isIE6 ? 'IE6' : isIE7 ? 'IE7' : isIE8 ? 'IE8' : 'IE';
} else if (isGecko){
    var isFF =  check(/firefox/);
    browserType = isFF ? 'Firefox' : 'Others';;
    jsType = isGecko2 ? 'Gecko2' : isGecko3 ? 'Gecko3' : 'Gecko';

    if(isFF){
        var versionStart = ua.indexOf('firefox') + 8;
        var versionEnd = ua.indexOf(' ', versionStart);
        if(versionEnd == -1){
            versionEnd = ua.length;
        }
        browserVersion = ua.substring(versionStart, versionEnd);
    }
} else if(isChrome){
    browserType = 'Chrome';
    jsType = isWebKit ? 'Web Kit' : 'Other';

    var versionStart = ua.indexOf('chrome') + 7;
    var versionEnd = ua.indexOf(' ', versionStart);
    browserVersion = ua.substring(versionStart, versionEnd);
}else{
    browserType = isOpera ? 'Opera' : isSafari ? 'Safari' : '';
}
于 2010-03-08T11:50:44.137 回答
29

以下是 2016 年检测浏览器的方法,包括 Microsoft Edge、Safari 10 和 Blink 检测:

// Opera 8.0+ (UA detection to detect Blink/v8-powered Opera)
isOpera = !!window.opera || navigator.userAgent.indexOf(' OPR/') >= 0;
// Firefox 1.0+
isFirefox = typeof InstallTrigger !== 'undefined';
// Safari 3.0+
isSafari = /constructor/i.test(window.HTMLElement) || (function (p) { return p.toString() === "[object SafariRemoteNotification]"; })(!window['safari'] || safari.pushNotification);
// Internet Explorer 6-11
isIE = /*@cc_on!@*/false || !!document.documentMode;
// Edge 20+
isEdge = !isIE && !!window.StyleMedia;
// Chrome 1+
isChrome = !!window.chrome && !!window.chrome.webstore;
// Blink engine detection
isBlink = (isChrome || isOpera) && !!window.CSS;

这种方法的美妙之处在于它依赖于浏览器引擎的属性,因此它甚至涵盖了衍生浏览器,例如 Yandex 或 Vivaldi,它们实际上与它们使用的引擎的主要浏览器兼容。Opera 是个例外,它依赖于用户代理嗅探,但今天(即 15 版及更高版本)甚至 Opera 本身也只是 Blink 的一个外壳。

于 2016-01-21T07:52:38.870 回答
16

通常最好尽可能避免使用特定于浏览器的代码。JQuery$.support属性可用于检测对特定功能的支持,而不是依赖于浏览器名称和版本。

例如,在 Opera 中,您可以伪造 Internet Explorer 或 firefox 实例。

替代文字

JQuery.support 的详细描述可以在这里找到:http: //api.jquery.com/jQuery.support/

现在根据 jQuery 已弃用。

我们强烈建议使用诸如Modernizr之类的外部库, 而不是依赖jQuery.support.

在编写网站代码时,我总是确保非 js 用户也可以使用导航等基本功能。这可能是讨论的对象,如果主页针对特殊受众,则可以忽略。

于 2010-03-08T11:37:19.453 回答
12

这会告诉您有关浏览器及其版本的所有详细信息。

<!DOCTYPE html>
<html>
<body>
<div id="example"></div>

<script>

txt = "<p>Browser CodeName: " + navigator.appCodeName + "</p>";
txt+= "<p>Browser Name: " + navigator.appName + "</p>";
txt+= "<p>Browser Version: " + navigator.appVersion + "</p>";
txt+= "<p>Cookies Enabled: " + navigator.cookieEnabled + "</p>";
txt+= "<p>Platform: " + navigator.platform + "</p>";
txt+= "<p>User-agent header: " + navigator.userAgent + "</p>";
txt+= "<p>User-agent language: " + navigator.systemLanguage + "</p>";

document.getElementById("example").innerHTML=txt;

</script>

</body>
</html>
于 2013-02-25T09:43:24.917 回答
7

有关 Web 浏览器的所有信息都包含在 navigator 对象中。名称和版本在那里。

var appname = window.navigator.appName;

来源:javascript浏览器检测

于 2012-10-04T09:15:49.567 回答
7
//Copy and paste this into your code/text editor, and try it

//Before you use this to fix compatability bugs, it's best to try inform the browser provider that you have found a bug and there latest browser may not be up to date with the current web standards

//Since none of the browsers use the browser identification system properly you need to do something a bit like this

//Write browser identification
document.write(navigator.userAgent + "<br>")

//Detect browser and write the corresponding name
if (navigator.userAgent.search("MSIE") >= 0){
    document.write('"MS Internet Explorer ');
    var position = navigator.userAgent.search("MSIE") + 5;
    var end = navigator.userAgent.search("; Windows");
    var version = navigator.userAgent.substring(position,end);
    document.write(version + '"');
}
else if (navigator.userAgent.search("Chrome") >= 0){
document.write('"Google Chrome ');// For some reason in the browser identification Chrome contains the word "Safari" so when detecting for Safari you need to include Not Chrome
    var position = navigator.userAgent.search("Chrome") + 7;
    var end = navigator.userAgent.search(" Safari");
    var version = navigator.userAgent.substring(position,end);
    document.write(version + '"');
}
else if (navigator.userAgent.search("Firefox") >= 0){
    document.write('"Mozilla Firefox ');
    var position = navigator.userAgent.search("Firefox") + 8;
    var version = navigator.userAgent.substring(position);
    document.write(version + '"');
}
else if (navigator.userAgent.search("Safari") >= 0 && navigator.userAgent.search("Chrome") < 0){//<< Here
    document.write('"Apple Safari ');
    var position = navigator.userAgent.search("Version") + 8;
    var end = navigator.userAgent.search(" Safari");
    var version = navigator.userAgent.substring(position,end);
    document.write(version + '"');
}
else if (navigator.userAgent.search("Opera") >= 0){
    document.write('"Opera ');
    var position = navigator.userAgent.search("Version") + 8;
    var version = navigator.userAgent.substring(position);
    document.write(version + '"');
}
else{
    document.write('"Other"');
}

//Use w3schools research the `search()` method as other methods are availible
于 2012-11-17T05:04:58.023 回答
6

由于 Internet Explorer 11 (IE11+) 出现并且不再使用标签名称,MSIE我想出了一个旧检测功能的变体:

navigator.sayswho= (function(){
    var N= navigator.appName, ua= navigator.userAgent, tem;

    // if IE11+
    if (new RegExp("Trident/.*rv:([0-9]{1,}[\.0-9]{0,})").exec(ua) !== null) {
        var M= ["Internet Explorer"];
        if(M && (tem= ua.match(/rv:([0-9]{1,}[\.0-9]{0,})/))!= null) M[2]= tem[1];
        M= M? [M[0], M[2]]: [N, navigator.appVersion,'-?'];
        return M;
    }

    var M= ua.match(/(opera|chrome|safari|firefox|msie)\/?\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;
})();
于 2014-09-30T05:07:25.230 回答
5

可悲的是,IE11 不再MSIE具有navigator.userAgent

Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; OfficeLiveConnector.1.5; OfficeLivePatch.1.3; .NET4.0C; BRI/2; BOIE9;ENUS; rv:11.0) like Gecko

至于为什么您想知道您使用的是哪个浏览器,这是因为每个浏览器都有自己的一组错误,并且您最终会实施特定于浏览器和版本的解决方法,或者告诉用户使用不同的浏览器!

于 2013-11-11T22:36:54.100 回答
4
var browser = navigator.appName;
var version = navigator.appVersion;

但是请注意,两者都不一定反映事实。许多浏览器可以设置为屏蔽为其他浏览器。因此,例如,您无法始终确定用户是使用 IE6 还是使用伪装成 IE6 的 Opera 进行冲浪。

于 2010-03-08T11:35:27.663 回答
3

这个小图书馆可以帮助你。但请注意,浏览器检测并不总是解决方案。

于 2010-03-08T11:42:38.583 回答
3

以下是我为 Internet Explorer 自定义 CSS 的方法:

在我的 JavaScript 文件中:

function isIE () {
      var myNav = navigator.userAgent.toLowerCase();
      return (myNav.indexOf('msie') != -1) ? parseInt(myNav.split('msie')[1]) : false;
}

jQuery(document).ready(function(){
    if(var_isIE){
            if(var_isIE == 10){
                jQuery("html").addClass("ie10");
            }
            if(var_isIE == 8){
                jQuery("html").addClass("ie8");
                // you can also call here some function to disable things that 
                //are not supported in IE, or override browser default styles.
            }
        }
    });

然后在我的 CSS 文件中,定义每种不同的样式:

.ie10 .some-class span{
    .......
}
.ie8 .some-class span{
    .......
}
于 2014-05-22T02:28:22.200 回答
3

如果你想要一个返回浏览器和版本的函数,这里是对原始答案的改进:

navigator.browserInfo = 
(
    function()
    {
        var browser = '';
        var version = '';
        var idString = '';

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

        //IE will be identified as 'Trident' and a different version number. The name must be corrected to 'Internet Explorer' and the correct version identified.
        //ie correction
        if(/trident/i.test(M[1]))
        {
            tem = /\brv[ :]+(\d+.?\d*)/g.exec(ua) || [];
            browser = 'Internet Explorer';
            version = tem[1];
        }

        //firefox
        else if(/firefox/i.test(M[1]))
        {
            tem = /\brv[ :]+(\d+.?\d*)/g.exec(ua) || [];
            browser = 'Firefox';
            version = tem[1];
        }

        //safari
        else if(/safari/i.test(M[1]))
        {
            tem = ua.match(/\bVersion\/(\d+.?\d*\s*\w+)/);
            browser = 'Safari';
            version = tem[1];
        }

        //If 'Chrome' is found, it may be another browser. 
        else if(M[1] === 'Chrome')
        {
            //opera
            var temOpr = ua.match(/\b(OPR)\/(\d+.?\d*.?\d*.?\d*)/);
            //edge
            var temEdge = ua.match(/\b(Edge)\/(\d+.?\d*)/);
            //chrome
            var temChrome = ua.match(/\b(Chrome)\/(\d+.?\d*.?\d*.?\d*)/);

            //a genuine 'Chrome' reading will result from ONLY temChrome not being null.
            var genuineChrome = temOpr == null && temEdge == null && temChrome != null;

            if(temOpr != null)
            {
                browser = temOpr[1].replace('OPR', 'Opera');
                version = temOpr[2];
            }

            if(temEdge != null)
            {
                browser = temEdge[1];
                version = temEdge[2];
            }

            if(genuineChrome)
            {
                browser = temChrome[1];
                version = temChrome[2];
            }
        }
        //There will be some odd balls, so if you wish to support those browsers, add functionality to display those browsers as well.

        if(browser == '' || version == '')
        {
            idString = 'We couldn\'t find your browser, but you can still use the site';
        }
        else
        {
            idString = browser + ' version ' + version;
        }

        alert('Your browser is ' + idString);

        //store the type of browser locally
        if(typeof(Storage) !== "undefined")
        {
            //Store
            localStorage.setItem('browser', browser);
            localStorage.setItem('version', version);
        } 
        else
        {
            alert('local storage not available');
        }
    }
)();

这样,它还将结果存储在本地,因此不必每次都运行此检查。

于 2014-05-30T08:34:00.683 回答
3

您可以扫描用户代理以查找浏览器名称,而不是硬编码 Web 浏览器:

navigator.userAgent.split(')').reverse()[0].match(/(?!Gecko|Version|[A-Za-z]+?Web[Kk]it)[A-Z][a-z]+/g)[0]

我已经在 Safari、Chrome 和 Firefox 上对此进行了测试。如果您发现这在浏览器上不起作用,请告诉我。

  • 苹果浏览器:"Safari"
  • 铬合金:"Chrome"
  • 火狐:"Firefox"

如果需要,您甚至可以修改它以获取浏览器版本。请注意有更好的方法来获取浏览器版本

navigator.userAgent.split(')').reverse()[0].match(/(?!Gecko|Version|[A-Za-z]+?Web[Kk]it)[A-Z][a-z]+\/[\d.]+/g)[0].split('/')

样本输出:

Firefox/39.0    
于 2015-08-07T22:05:45.103 回答
2

这就是我正在使用的:

var ua = navigator.userAgent;
var info = {
        browser: /Edge\/\d+/.test(ua) ? 'ed' : /MSIE 9/.test(ua) ? 'ie9' : /MSIE 10/.test(ua) ? 'ie10' : /MSIE 11/.test(ua) ? 'ie11' : /MSIE\s\d/.test(ua) ? 'ie?' : /rv\:11/.test(ua) ? 'ie11' : /Firefox\W\d/.test(ua) ? 'ff' : /Chrom(e|ium)\W\d|CriOS\W\d/.test(ua) ? 'gc' : /\bSafari\W\d/.test(ua) ? 'sa' : /\bOpera\W\d/.test(ua) ? 'op' : /\bOPR\W\d/i.test(ua) ? 'op' : typeof MSPointerEvent !== 'undefined' ? 'ie?' : '',
        os: /Windows NT 10/.test(ua) ? "win10" : /Windows NT 6\.0/.test(ua) ? "winvista" : /Windows NT 6\.1/.test(ua) ? "win7" : /Windows NT 6\.\d/.test(ua) ? "win8" : /Windows NT 5\.1/.test(ua) ? "winxp" : /Windows NT [1-5]\./.test(ua) ? "winnt" : /Mac/.test(ua) ? "mac" : /Linux/.test(ua) ? "linux" : /X11/.test(ua) ? "nix" : "",
        touch: 'ontouchstart' in document.documentElement,
        mobile: /IEMobile|Windows Phone|Lumia/i.test(ua) ? 'w' : /iPhone|iP[oa]d/.test(ua) ? 'i' : /Android/.test(ua) ? 'a' : /BlackBerry|PlayBook|BB10/.test(ua) ? 'b' : /Mobile Safari/.test(ua) ? 's' : /webOS|Mobile|Tablet|Opera Mini|\bCrMo\/|Opera Mobi/i.test(ua) ? 1 : 0,
        tablet: /Tablet|iPad/i.test(ua),
};

info特性:

  • browsergc对于谷歌浏览器;ie9-ie11对于 IE;ie?对于旧的或未知的 IE;ed对于边缘;ff对于火狐;sa对于 Safari;op歌剧。
  • osmac win7 win8 win10 winnt winxp winvista linux nix
  • mobilea适用于安卓;i适用于 iOS(iPhone iPad);w对于 Windows 手机;b黑莓;s对于未检测到的正在运行 Safari 的移动设备;1对于其他未被检测到的手机;0对于非移动设备
  • touchtrue适用于支持触控的设备,包括同时具有鼠标和触控功能的触控笔记本电脑/笔记本电脑;false无触摸支持
  • tablettruefalse

https://jsfiddle.net/oriadam/ncb4n882/

于 2016-08-14T20:15:49.533 回答
1

您可以使用 jQuery 库来检测浏览器版本。

例子:

jQuery.browser.version

但是,这仅在您还使用 jQuery 的其他功能时才有意义。添加整个库只是为了检测浏览器对我来说似乎有点矫枉过正。

更多信息: http ://api.jquery.com/jQuery.browser/

(你必须向下滚动一点)

于 2010-03-08T12:22:32.200 回答
1
 var isOpera = !!window.opera || navigator.userAgent.indexOf('Opera') >= 0;
        // Opera 8.0+ (UA detection to detect Blink/v8-powered Opera)
        var isFirefox = typeof InstallTrigger !== 'undefined';   // Firefox 1.0+
        var isSafari = Object.prototype.toString.call(window.HTMLElement).indexOf('Constructor') > 0;
        // At least Safari 3+: "[object HTMLElementConstructor]"
        var isChrome = !!window.chrome;                          // Chrome 1+
        var isIE = /*@cc_on!@*/false; 

您可以阅读更多 如何检测 Safari、Chrome、IE、Firefox 和 Opera 浏览器?

于 2013-06-27T07:10:46.373 回答
1

我知道我在这个问题上已经很晚了,但我想我会把我的片段放在这里。这里的很多答案都可以,而且,正如有人指出的那样,通常最好使用feature detection而不是依赖userAgent字符串。但是,如果你要走那条路,我已经写了一个完整的代码片段,以及一个替代的 jQuery 实现来替换 deprericated $.browser


香草JS

我的第一个片段只是向navigator对象添加了四个属性:browser, version, mobile, & webkit

jsFiddle


/** navigator [extended]
 *  Simply extends Browsers navigator Object to include browser name, version number, and mobile type (if available).
 *
 *  @property {String} browser The name of the browser.
 *  @property {Double} version The current Browser version number.
 *  @property {String|Boolean} mobile Will be `false` if is not found to be mobile device. Else, will be best guess Name of Mobile Device (not to be confused with browser name)
 *  @property {Boolean} webkit If is webkit or not.
 */
;(function(){function c(){try{switch(!0){case /MSIE|Trident/i.test(navigator.userAgent):return"MSIE";case /Chrome/.test(navigator.userAgent):return"Chrome";case /Opera/.test(navigator.userAgent):return"Opera";case /Kindle|Silk|KFTT|KFOT|KFJWA|KFJWI|KFSOWI|KFTHWA|KFTHWI|KFAPWA|KFAPWI/i.test(navigator.userAgent):return/Silk/i.test(navigator.userAgent)?"Silk":"Kindle";case /BlackBerry/.test(navigator.userAgent):return"BlackBerry";case /PlayBook/.test(navigator.userAgent):return"PlayBook";case /BB[0-9]{1,}; Touch/.test(navigator.userAgent):return"Blackberry";
case /Android/.test(navigator.userAgent):return"Android";case /Safari/.test(navigator.userAgent):return"Safari";case /Firefox/.test(navigator.userAgent):return"Mozilla";case /Nokia/.test(navigator.userAgent):return"Nokia"}}catch(a){console.debug("ERROR:setBrowser\t",a)}}function d(){try{switch(!0){case /Sony[^ ]*/i.test(navigator.userAgent):return"Sony";case /RIM Tablet/i.test(navigator.userAgent):return"RIM Tablet";case /BlackBerry/i.test(navigator.userAgent):return"BlackBerry";case /iPhone/i.test(navigator.userAgent):return"iPhone";
case /iPad/i.test(navigator.userAgent):return"iPad";case /iPod/i.test(navigator.userAgent):return"iPod";case /Opera Mini/i.test(navigator.userAgent):return"Opera Mini";case /IEMobile/i.test(navigator.userAgent):return"IEMobile";case /BB[0-9]{1,}; Touch/i.test(navigator.userAgent):return"BlackBerry";case /Nokia/i.test(navigator.userAgent):return"Nokia";case /Android/i.test(navigator.userAgent):return"Android"}}catch(a){console.debug("ERROR:setMobile\t",a)}return!1}function e(){try{switch(!0){case /MSIE|Trident/i.test(navigator.userAgent):return/Trident/i.test(navigator.userAgent)&&
/rv:([0-9]{1,}[\.0-9]{0,})/.test(navigator.userAgent)?parseFloat(navigator.userAgent.match(/rv:([0-9]{1,}[\.0-9]{0,})/)[1].replace(/[^0-9\.]/g,"")):/MSIE/i.test(navigator.userAgent)&&0<parseFloat(navigator.userAgent.split("MSIE")[1].replace(/[^0-9\.]/g,""))?parseFloat(navigator.userAgent.split("MSIE")[1].replace(/[^0-9\.]/g,"")):"Edge";case /Chrome/.test(navigator.userAgent):return parseFloat(navigator.userAgent.split("Chrome/")[1].split("Safari")[0].replace(/[^0-9\.]/g,""));case /Opera/.test(navigator.userAgent):return parseFloat(navigator.userAgent.split("Version/")[1].replace(/[^0-9\.]/g,
""));case /Kindle|Silk|KFTT|KFOT|KFJWA|KFJWI|KFSOWI|KFTHWA|KFTHWI|KFAPWA|KFAPWI/i.test(navigator.userAgent):if(/Silk/i.test(navigator.userAgent))return parseFloat(navigator.userAgent.split("Silk/")[1].split("Safari")[0].replace(/[^0-9\.]/g,""));if(/Kindle/i.test(navigator.userAgent)&&/Version/i.test(navigator.userAgent))return parseFloat(navigator.userAgent.split("Version/")[1].split("Safari")[0].replace(/[^0-9\.]/g,""));case /BlackBerry/.test(navigator.userAgent):return parseFloat(navigator.userAgent.split("/")[1].replace(/[^0-9\.]/g,
""));case /PlayBook/.test(navigator.userAgent):case /BB[0-9]{1,}; Touch/.test(navigator.userAgent):case /Safari/.test(navigator.userAgent):return parseFloat(navigator.userAgent.split("Version/")[1].split("Safari")[0].replace(/[^0-9\.]/g,""));case /Firefox/.test(navigator.userAgent):return parseFloat(navigator.userAgent.split(/Firefox\//i)[1].replace(/[^0-9\.]/g,""));case /Android/.test(navigator.userAgent):return parseFloat(navigator.userAgent.split("Version/")[1].split("Safari")[0].replace(/[^0-9\.]/g,
""));case /Nokia/.test(navigator.userAgent):return parseFloat(navigator.userAgent.split("Browser")[1].replace(/[^0-9\.]/g,""))}}catch(a){console.debug("ERROR:setVersion\t",a)}}a:{try{if(navigator&&navigator.userAgent){navigator.browser=c();navigator.mobile=d();navigator.version=e();var b;b:{try{b=/WebKit/i.test(navigator.userAgent);break b}catch(a){console.debug("ERROR:setWebkit\t",a)}b=void 0}navigator.webkit=b;break a}}catch(a){}throw Error("Browser does not support `navigator` Object |OR| has undefined `userAgent` property.");
}})();
/*  simple c & p of above   */

于 2015-03-27T17:36:05.790 回答
1
var isOpera = !!window.opera || navigator.userAgent.indexOf(' OPR/') >= 0;
    // Opera 8.0+ (UA detection to detect Blink/v8-powered Opera)
var isFirefox = typeof InstallTrigger !== 'undefined';   // Firefox 1.0+
var isSafari = Object.prototype.toString.call(window.HTMLElement).indexOf('Constructor') > 0;
    // At least Safari 3+: "[object HTMLElementConstructor]"
var isChrome = !!window.chrome && !isOpera;              // Chrome 1+
var isIE = /*@cc_on!@*/false || !!document.documentMode;
// Edge 20+
var isEdge = !isIE && !!window.StyleMedia;
// Chrome 1+
var output = 'Detecting browsers by ducktyping:<hr>';
output += 'isFirefox: ' + isFirefox + '<br>';
output += 'isChrome: ' + isChrome + '<br>';
output += 'isSafari: ' + isSafari + '<br>';
output += 'isOpera: ' + isOpera + '<br>';
output += 'isIE: ' + isIE + '<br>';
output += 'isIE Edge: ' + isEdge + '<br>';
document.body.innerHTML = output;
于 2017-06-27T05:45:11.443 回答
0

不完全是你想要的,但接近它:

var jscriptVersion = /*@cc_on @if(@_jscript) @_jscript_version @else @*/ false /*@end @*/;
var geckoVersion = navigator.product === 'Gecko' && navigator.productSub;
var operaVersion = 'opera' in window && 'version' in opera && opera.version();

变量将包含适当的版本,或者false如果它不可用。

如果有人使用 Chrome 可以了解您是否可以window.chrome以类似的方式使用window.opera.

于 2010-03-08T13:24:44.557 回答
0

我发现了一些有趣且更快的方法。IE 支持navigator.systemLanguagewhich 返回 "en-US" where 其他浏览器返回undefined

<script>
    var lang = navigator.systemLanguage;
    if (lang!='en-US'){document.write("Well, this is not internet explorer");}
    else{document.write("This is internet explorer");}
</script>
于 2014-04-18T17:15:09.963 回答
0

有时我们需要简单的方法来检查浏览器是否为 IE。这可能是这样的:

 var isMSIE = (/trident/i).test(navigator.userAgent);

 if(isMSIE)
 {
  /* do something for ie */
 }
 else
 {
  /* do something else */
 }

或简化 siva 的方法:

 if(!!navigator.systemLanguage)
 {
  /* do something for ie */
 }
 else
 {
  /* do something else */
 }

MSIE v.11 检查:

if( (/trident/i).test(navigator.userAgent) && (/rv:/i).test(navigator.userAgent) )
{
  /* do something for ie 11 */
}

其他 IE 浏览器在其 userAgent 属性中包含 MSIE 字符串,并且可以被它捕获。

于 2014-07-04T15:58:33.120 回答
0

我做了这个小功能,希望对您有所帮助。在这里你可以找到最新版本的 browserDetection

function detectBrowser(userAgent){
  var chrome  = /.*(Chrome\/).*(Safari\/).*/g;
  var firefox = /.*(Firefox\/).*/g;
  var safari  = /.*(Version\/).*(Safari\/).*/g;
  var opera   = /.*(Chrome\/).*(Safari\/).*(OPR\/).*/g

  if(opera.exec(userAgent))
    return "Opera"
  if(chrome.exec(userAgent))
    return "Chrome"
  if(safari.exec(userAgent))
    return "Safari"
  if(firefox.exec(userAgent))
    return "Firefox"
}
于 2016-06-16T16:16:09.170 回答
-1

下面的代码片段将展示如何根据 IE 版本和浏览器显示 UI 元素

$(document).ready(function () {

var msiVersion = GetMSIieversion();
if ((msiVersion <= 8) && (msiVersion != false)) {

    //Show UI elements specific to IE version 8 or low

    } else {
    //Show UI elements specific to IE version greater than 8 and for other browser other than IE,,ie..Chrome,Mozila..etc
    }
}
);

下面的代码将给出我们如何获得 IE 版本

function GetMSIieversion() {

var ua = window.navigator.userAgent;
var msie = ua.indexOf('MSIE ');
if (msie > 0) {
    // IE 10 or older => return version number
    return parseInt(ua.substring(msie + 5, ua.indexOf('.', msie)), 10);
}

var trident = ua.indexOf('Trident/');
if (trident > 0) {
    // IE 11 => return version number
    var rv = ua.indexOf('rv:');
    return parseInt(ua.substring(rv + 3, ua.indexOf('.', rv)), 10);
}

var edge = ua.indexOf('Edge/');
if (edge > 0) {
    // Edge (IE 12+) => return version number
    return parseInt(ua.substring(edge + 5, ua.indexOf('.', edge)), 10);
}

// other browser like Chrome,Mozila..etc
return false;

}
于 2017-12-08T12:36:40.797 回答