js如何判断浏览器

JavaScript09

js如何判断浏览器,第1张

<script type=“text/javascript”>

function isIE(){

return navigator.appName.indexOf(“Microsoft Internet Explorer”)!=-1 &&document.all

}

function isIE6() {

return navigator.userAgent.split(“”)[1].toLowerCase().indexOf(“msie 6.0″)==“-1″?false:true

}

function isIE7(){

return navigator.userAgent.split(“”)[1].toLowerCase().indexOf(“msie 7.0″)==“-1″?false:true

}

function isIE8(){

return navigator.userAgent.split(“”)[1].toLowerCase().indexOf(“msie 8.0″)==“-1″?false:true

}

function isNN(){

return navigator.userAgent.indexOf(“Netscape”)!=-1

}

function isOpera(){

return navigator.appName.indexOf(“Opera”)!=-1

}

function isFF(){

return navigator.userAgent.indexOf(“Firefox”)!=-1

}

function isChrome(){

return navigator.userAgent.indexOf(“Chrome”) >-1

}

</script>

下面介绍下 js获取客户端浏览器信息

Navigator 对象包含有关浏览器的信息。js就是通过Navigator的属性获取客户端浏览器信息

Navigator 对象属性:

属性

描述

appCodeName 返回浏览器的代码名。

appMinorVersion返回浏览器的次级版本。

appName 返回浏览器的名称。

appVersion 返回浏览器的平台和版本信息。

browserLanguage返回当前浏览器的语言。

cookieEnabled 返回指明浏览器中是否启用 cookie 的布尔值。

cpuClass 返回浏览器系统的 CPU 等级。

onLine 返回指明系统是否处于脱机模式的布尔值。

platform 返回运行浏览器的操作系统平台。

systemLanguage返回 OS 使用的默认语言。

userAgent 返回由客户机发送服务器的 user-agent 头部的值。

userLanguage返回 OS 的自然语言设置。

前几天在网上看到一个技术牛人写的世界上判断是否IE浏览器之最短的js代码,如下:<scriptif(!+[1,])alert(这是ie浏览器)

else alert(这不是ie浏览器)

</script

其实有很多判断的方法,大都是根据浏览器的特性来的。

比如库prototype的方法是:!!(window.attachEvent &&navigator.userAgent.indexOf('Opera') === -1) 。就是根据ie支持window.attachEvent添加侦听事件,非ie用window.addEventListener添加侦听事件来判断的。navigator.userAgent.indexOf('Opera') === -1是因为opara浏览器能伪装成ie.如果!!(window.attachEvent )为真,就是ie;反之,如果!window.addEventListener为真,也可以判断为ie.

Ext使用的是!1[0],他利用IE无法使用数组下标访问字符串的特性来判断。在ie8下好像有问题。

在!+[1,]还未被发现前,判断ie最短的表达式是 !+\v1.它利用的是ie不支持垂直制表符的特性。

以前还有一个常用方法是document.all,由于opera浏览器能伪装成ie。可以这样写:!!(document.all &&navigator.userAgent.indexOf('Opera') === -1).

还有很多,先记这几条,便于工作时查阅。

1.+[1,]

2.!+\v1

3.!!(window.attachEvent &&navigator.userAgent.indexOf('Opera') === -1)

4.!!(!window.addEventListener&&navigator.userAgent.indexOf('Opera') === -1)

5.!!(document.all &&navigator.userAgent.indexOf('Opera') === -1)