JavaScript中的浏览器检测?

Pro*_*cop 218 javascript browser-detection

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

ken*_*bec 351

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').replace('Edg ', 'Edge ');
    }
    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(' ');
})();
Run Code Online (Sandbox Code Playgroud)

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

当您在多个浏览器上测试新代码时,它对于排序测试和错误结果很方便.

  • 我喜欢这个!谢啦!不过,我只是对第一行和第二行进行了修改.我更换了:`navigator.sayswho =`在第一行使用`navigator.browserInfo =`以获得更好的可读性(即所以我不会怀疑它在几个月后它在代码中做了什么)并替换了`return M.join(''' );```return {'browser':M [0],'version':M [1]};`这样我就可以在全局范围内使用它:`console.log(navigator.browserInfo.browser );`和`console.log(navigator.browserInfo.version);`以获得更好的可访问性.对不起,我想我确实搞砸了它,即使它说"不要碰". (32认同)
  • 来自我的+1.有时候,它不是关于功能支持,而是关于浏览器.是的,用户代理信息可能是欺骗性的,但是当您处理旧浏览器并规避它们的错误时(如FF 3的问题而没有为只读AJAX POST消息发送Content-Length标头),功能支持就是不会削减它. (14认同)
  • 这段代码几乎不可读。什么是“tem”?什么是‘M’? (3认同)
  • 很高兴知道这个函数返回的所有结果...... (2认同)

小智 62

我建议使用小型的JavaScript库Bowser,是的没有r.它基于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');
}
Run Code Online (Sandbox Code Playgroud)


Aru*_*hny 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' : '';
}
Run Code Online (Sandbox Code Playgroud)

  • 总是运行所有检查是不是有点浪费?如果你知道它不是它,那么检查Linux似乎毫无意义...... (7认同)
  • 我所看到的就是`var var var var var var var ... 确实没有必要,这对于使用OCD的项目经理来说是一个痛苦的阅读。 (2认同)

pil*_*lau 26

以下是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;
Run Code Online (Sandbox Code Playgroud)

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

  • 这个页面中唯一正确的答案.在最新的IE版本之后,Navigator对象不再可靠. (2认同)
  • 有关这些测试所依据的文档,请查看其他答案:/sf/answers/689623861/ (2认同)

Phi*_*off 16

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

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

替代文字

有关JQuery.support的详细说明,请访问:http://api.jquery.com/jQuery.support/

现在根据jQuery弃用了.

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

在对网站进行编码时,我始终确保非js用户也可以访问导航等基本功能.这可能是讨论的对象,如果主页面向特定受众,则可以忽略.

  • 有时您需要知道浏览器版本.请务必回答问题. (31认同)
  • 有时,当以不同的方式支持相同的功能时,您确实需要了解浏览器.因此,如果使用jQuery,$ .browser是正确的方法,如user288744所示 (21认同)
  • @PhilRykoff - 但是你没有回答99%的问题 - 你正在回答另一个问题的99%的案例,你认为提问者打算问,或者应该问.也许先要求澄清一下? (8认同)

mal*_*lmX 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>
Run Code Online (Sandbox Code Playgroud)

  • '在我的机器上工作'是不可接受的Web开发方法. (5认同)
  • 看起来我的所有浏览器都是Netscape.要么你的代码很糟糕,要么我很高 (3认同)

小智 8

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

var appname = window.navigator.appName;
Run Code Online (Sandbox Code Playgroud)

来源:javascript浏览器检测

  • Chrome称"Netscape" (33认同)
  • XP上的Firefox 20.0.1也说"Netscape". (4认同)
  • appCodeName = Mozilla和appName = Chrome 33中的Netscape (3认同)
  • Firefox和Chrome称'Netscape'.IE 8什么也没说! (2认同)

Way*_*mer 6

//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
Run Code Online (Sandbox Code Playgroud)

  • 请不要推荐w3schools (7认同)

ghi*_*ing 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;
})();
Run Code Online (Sandbox Code Playgroud)


小智 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
Run Code Online (Sandbox Code Playgroud)

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