判断浏览器的类型
程序员文章站
2024-02-01 16:26:52
...
用js判断浏览器的类型有很多方法,典型的是根据navigator.userAgent或浏览器的不同js特征等。
1. 根据navigator.userAgent判断
在页面中加入:
结果示例:
IE9
userAgent: Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; InfoPath.2; MS-RTC LM 8; .NET4.0C; .NET4.0E)
product: undefined
Firefox 13.0.1
userAgent: Mozilla/5.0 (Windows NT 6.1; rv:13.0) Gecko/20100101 Firefox/13.0.1
product: Gecko
Chrome 20.0.1132.47 m
userAgent: Mozilla/5.0 (Windows NT 6.1) AppleWebKit/536.11 (KHTML, like Gecko) Chrome/20.0.1132.47 Safari/536.11
product: Gecko
Safari 5.1.1
userAgent: Mozilla/5.0 (Windows NT 6.1) AppleWebKit/534.51.22 (KHTML, like Gecko) Version/5.1.1 Safari/534.51.22
product: Gecko
代码示例:
2. 根据浏览器特征
1. 根据navigator.userAgent判断
在页面中加入:
<script type="text/javascript"> alert(navigator.userAgent); alert(navigator.product); </script>
结果示例:
IE9
userAgent: Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; InfoPath.2; MS-RTC LM 8; .NET4.0C; .NET4.0E)
product: undefined
Firefox 13.0.1
userAgent: Mozilla/5.0 (Windows NT 6.1; rv:13.0) Gecko/20100101 Firefox/13.0.1
product: Gecko
Chrome 20.0.1132.47 m
userAgent: Mozilla/5.0 (Windows NT 6.1) AppleWebKit/536.11 (KHTML, like Gecko) Chrome/20.0.1132.47 Safari/536.11
product: Gecko
Safari 5.1.1
userAgent: Mozilla/5.0 (Windows NT 6.1) AppleWebKit/534.51.22 (KHTML, like Gecko) Version/5.1.1 Safari/534.51.22
product: Gecko
代码示例:
var isOpera = (navigator.userAgent.indexOf("Opera") != -1); var isMSIE = (navigator.userAgent.indexOf("MSIE") != -1) && (!isOpera); var isGecko = (navigator.userAgent.indexOf("Gecko") != -1) && (!isOpera); var isChrome = (navigator.userAgent.indexOf("Chrome") != -1); var isSafari = (navigator.userAgent.indexOf("Safari") != -1) && (!isChrome);
2. 根据浏览器特征
// IE document.all window.event window.attachEvent // Firefox window.addEventListener