【发布时间】:2011-09-24 04:54:06
【问题描述】:
任何人都知道使用 JavaScript/jQuery 找出安装在客户端上的浏览器的类型和版本的可靠方法吗?
看起来 jQuery 有一些内置函数,但它在检测 Chrome 时遇到了问题。还有其他可靠的方法吗?
【问题讨论】:
任何人都知道使用 JavaScript/jQuery 找出安装在客户端上的浏览器的类型和版本的可靠方法吗?
看起来 jQuery 有一些内置函数,但它在检测 Chrome 时遇到了问题。还有其他可靠的方法吗?
【问题讨论】:
由于 $.browser 在 jQuery 1.9 中被删除,使用这个:
// ----------------------------------------------------------
// A short snippet for detecting versions of IE in JavaScript
// without resorting to user-agent sniffing
// ----------------------------------------------------------
// If you're not in IE (or IE version is less than 5) then:
// ie === undefined
// If you're in IE (>=5) then you can determine which version:
// ie === 7; // IE7
// Thus, to detect IE:
// if (ie) {}
// And to detect the version:
// ie === 6 // IE6
// ie > 7 // IE8, IE9 ...
// ie < 9 // Anything less than IE9
// ----------------------------------------------------------
// UPDATE: Now using Live NodeList idea from @jdalton
var ie = (function(){
var undef,
v = 3,
div = document.createElement('div'),
all = div.getElementsByTagName('i');
while (
div.innerHTML = '<!--[if gt IE ' + (++v) + ']><i></i><![endif]-->',
all[0]
);
return v > 4 ? v : undef;
}());
【讨论】:
如果您想了解访问者使用的浏览器的信息,并将其用于统计或向用户显示信息,您可以使用jQuery Browser Plugin。
它在 javascript 中为您提供了一个对象 包含所有信息 关于正在使用的浏览器。
当您想确定浏览器中的某个功能是否可用、应用错误修复等时,请务必使用do feature detection 而不是浏览器检测。
无需重新发明轮子。
【讨论】:
方法 1:
注意: 自 JQuery 1.3 起,jQuery.browser 已被弃用
试试这个:
<!DOCTYPE html>
<html>
<head>
<style>
p { color:green; font-weight:bolder; margin:3px 0 0 10px; }
div { color:blue; margin-left:20px; font-size:14px; }
span { color:red; }
</style>
<script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
<p>Browser info: (key : value)</p>
<script>
jQuery.each(jQuery.browser, function(i, val) {
$("<div>" + i + " : <span>" + val + "</span>")
.appendTo( document.body );
});</script>
</body>
</html>
方法 2:
// A quick solution without using regexp (to speed up a little).
var userAgent = navigator.userAgent.toString().toLowerCase();
if ((userAgent.indexOf('safari') != -1) && !(userAgent.indexOf('chrome') != -1)) {
alert('We should be on Safari only!');
}
【讨论】:
$.browser 自 jQuery 1.3 以来已被弃用。 @Arjun 您的目标是向用户显示浏览器名称和版本吗?