如何使用JavaScript确定确切的浏览器和版本?
当前回答
由于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;
})();
其他回答
这将告诉您有关浏览器及其版本的所有详细信息。
<!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>
下面是我如何为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{
.......
}
通常最好尽可能避免使用特定于浏览器的代码。JQuery $。属性可用于检测对特定特性的支持,而不是依赖于浏览器名称和版本。
以Opera为例,你可以伪造internet explorer或firefox实例。
JQuery的详细描述。支持可以在这里找到:http://api.jquery.com/jQuery.support/
现在根据jQuery弃用。
我们强烈建议使用外部库,如Modernizr 而不是依赖于jQuery.support中的属性。
在编写网站代码时,我总是确保,像导航这样的基本功能对非js用户也是可以访问的。这可能是讨论的对象,如果主页是针对特殊受众,可以忽略。
var browser = navigator.appName;
var version = navigator.appVersion;
然而,请注意,两者并不一定反映事实。许多浏览器都可以设置为其他浏览器的掩码。例如,你不能总是确定用户是用IE6还是用伪装成IE6的Opera上网。
所有关于web浏览器的信息都包含在navigator对象中。名字和版本都在那里。
var appname = window.navigator.appName;
来源:javascript浏览器检测