JavaScript中的浏览器检测?

233

如何使用JavaScript确定浏览器和版本信息?


确保您不要将关键功能基于此测试。 - Joe Ratzer
这里有一个更好的链接来解释对象检测:http://www.quirksmode.org/js/support.html - kmote
其他相关答案可以在这个这个重复问题中找到。 - Matthijs Wessels
25个回答

4
var browser = navigator.appName;
var version = navigator.appVersion;

请注意,这两个值并不一定反映真实情况。许多浏览器可以设置为伪装成其他浏览器。因此,例如,您不能始终确定用户是实际上使用IE6还是伪装成IE6的Opera浏览器浏览。


1
+1:与之前的负投票相反,理论上这是正确的方法;但在实践中,浏览器供应商会用可疑的内容填充这些值;请参阅 MDC(https://developer.mozilla.org/En/DOM/Window.navigator)和 MSDN(http://msdn.microsoft.com/en-us/library/ms535867%28VS.85%29.aspx)文档;谷歌还引导我到了以下页面(已过时,没有 Chrome),该页面显示主要是 Safari 报告垃圾信息:http://www.javascriptkit.com/jsref/navigator.shtml - Christoph
甚至在理论上也不是正确的方式——请参阅HTML5规范6.5.1.1客户端标识部分,其中对navigator.appName说:必须返回字符串“Netscape”或浏览器的完整名称,例如“Mellblom Browsernator”。换句话说,HTML5标准甚至没有假装要求appName具有有意义的值。 - Spike0xff
@Spike0xff 这个答案出自于一个时代,那时几乎没有人在使用HTML5,甚至可能也从未听说过它。 - ЯegDwight
@ЯegDwight(或者我应该说Elton?):在几乎所有的浏览器中,“navigator.appName”一直是“Netscape”或空,早在HTML5规范规定这种做法之前就已经存在了。 - T.J. Crowder
PHP使用可选的browsercap.ini来实现此功能。您可以从browscap.org下载所有可能的用户代理字符串。您会发现它非常复杂。此外,所有以HTTP_开头的标头都可能被伪造。 - B.F.

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{
    .......
}

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');
        }
    }
)();

同时,它还会在本地存储结果,因此不必每次都运行此检查。


这几乎是被接受答案的一个完全复制。请注意,@kennebec的解决方案返回浏览器名称和版本,而此版本仅返回浏览器名称。 - smholloway

3
这个小库可能会对你有所帮助。但请注意,浏览器检测并不总是解决方案。

1
那么,解决方案是什么?你如何制作依赖于浏览器或其版本的样式/功能? - Francisco Corrales Morales

3

不要硬编码网页浏览器,可以扫描用户代理来查找浏览器名称:

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

我已在Safari、Chrome和Firefox上测试过。如果您发现在某个浏览器上无法正常工作,请告诉我。

  • Safari: "Safari"
  • Chrome: "Chrome"
  • Firefox: "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    

1
不适用于某些不同的浏览器 - 它将UCBrowser指向Chrome,即使在IE兼容模式下,哈哈 - Malavos
它说Edge是Chrome... - goodhyun

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属性:

  • browser:对于Google Chrome,值为gc;对于IE,值为ie9-ie11;对于旧版或未知版本的IE,值为ie?;对于Edge,值为ed;对于Firefox,值为ff;对于Safari,值为sa;对于Opera,值为op
  • os:值为macwin7win8win10winntwinxpwinvistalinuxnix
  • mobile:对于Android,值为a;对于iOS(iPhone iPad),值为i;对于Windows Phone,值为w;对于Blackberry,值为b;对于运行Safari的未检测到的移动设备,值为s;对于其他未检测到的移动设备,值为1;对于非移动设备,值为0
  • touch:对于支持触摸的设备(包括同时支持鼠标和触摸的触摸笔记本电脑),值为true;对于不支持触摸的设备,值为false
  • tablet:值为truefalse

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


1

我知道我来晚了,但是我想分享一些代码片段。这里有很多答案还好,正如其中一个指出的那样,最好使用“特性检测”而不是依赖于“userAgent”字符串。然而,如果你要走这条路线,我已经写了一个完整的代码片段,以及一个替代jQuery实现来替换已废弃的“$.browser”。


原生JS

我的第一个代码片段只是向navigator对象添加了四个属性:browserversionmobilewebkit

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   */


我尝试了你的代码(使用原生JS)... 当我在移动浏览器中使用Firefox和Opera尝试时,它没有给出正确的输出。 - Raja Dhasan
@RajaDhasan 香草版本已更新。现在试试吧。 - SpYk3HH
它在网页浏览器中完美运行...但是当我尝试从Android手机上的Chrome浏览器运行时,它会打印出“Android”,而在Opera浏览器中则会打印出“Chrome”。 - Raja Dhasan

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;

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浏览器?


1
你可以使用jQuery库来检测浏览器版本。
示例:

jQuery.browser.version

然而,只有在您还使用jQuery的其他功能时,这才有意义。仅为检测浏览器添加整个库似乎对我来说有些过度。

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

(您需要向下滚动一点)


我刚在Win 8 Chrome 25和IE 10上尝试了一下。很遗憾,它完全失败了。经过三年后,任何当前的支持都会很好。 - Cihad Turhan
8
这个功能在jQuery 1.3被弃用,最终在jQuery 1.9中被删除。因此,最好不要依赖它。 - Metalcoder

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接