我正在尝试使用这行代码来检测浏览器类型:IE或Firefox。
alert(isBrowser("Microsoft"));
但是我什么都没有得到,甚至弹出警报也没有。不确定我做错了什么。
检测浏览器类型的最佳实践方式是什么?
我正在尝试使用这行代码来检测浏览器类型:IE或Firefox。
alert(isBrowser("Microsoft"));
但是我什么都没有得到,甚至弹出警报也没有。不确定我做错了什么。
检测浏览器类型的最佳实践方式是什么?
试试这个:
alert(navigator.appName);
我认为jQuery做得很好,当他们支持测试特性而不仅仅是浏览器时。
如果要检测MSIE浏览器,您可以使用JavaScript:
// This function returns Internet Explorer's major version number,
// or 0 for others. It works by finding the "MSIE " string and
// extracting the version number following the space, up to the decimal
// point, ignoring the minor version number
<SCRIPT LANGUAGE="JavaSCRIPT">
function msieversion()
{
var ua = window.navigator.userAgent
var msie = ua.indexOf ( "MSIE " )
if ( msie > 0 ) // If Internet Explorer, return version number
return parseInt (ua.substring (msie+5, ua.indexOf (".", msie )))
else // If another browser, return 0
return 0
}
</SCRIPT>
<SCRIPT LANGUAGE="javascript">
if ( msieversion() >= 0 )
document.write ( "This is Internet Explorer" );
else
document.write ( "This is another browser" );
</SCRIPT>
http://support.microsoft.com/kb/167820 http://support.microsoft.com/kb/167820
关于这个问题,Quirksmode上有一篇非常好的文章:http://www.quirksmode.org/js/support.html
'lajuette'提供的脚本很好,但它并不能让你变得更聪明。同一位作者在上面的链接中解释了他编写脚本的思路,基本上他说:
function whereUWantToDetectBrowser(){
if (navigator.appName == "Microsoft Internet Explorer")
intExp();
else
other();
}
function intExp(){
//do what you want to do for specifically Internet Explorer
}
function other(){
//do what you want to do for other browsers
}
这段代码解决了问题。如果你在whereUWantToDetectBrowser()
中调用函数,而是在那里编写你的特定代码,这将导致错误。代码将无法运行。因为浏览器检测它必须运行的代码(对于每个浏览器都是特定的)。如果你区分代码,意味着代码在某些浏览器中不起作用,所以你想要为这些浏览器专门编写代码。
因此,在IE中,other()
没有效果,就像在其他浏览器中intExp()
没有效果一样。
查找IE浏览器类型的最佳且最短的方法是...您可以对其他浏览器类型执行相同操作
if (navigator.appName == "Microsoft Internet Explorer"){
// Ur piece of validation
}