var userAgent = navigator.userAgent //取得浏览器的userAgent字符串
var isOpera = userAgent.indexOf("Opera") > -1
if (isOpera) {
return "Opera"
} //判断是否Opera浏览器
if (userAgent.indexOf("Firefox") > -1) {
return "FF"
} //判断是否Firefox浏览器
if (userAgent.indexOf("Chrome") > -1){
return "Chrome"
}
if (userAgent.indexOf("Safari") > -1) {
return "Safari"
} //判断是否Safari浏览器
if (userAgent.indexOf("compatible") > -1 && userAgent.indexOf("MSIE") > -1 && !isOpera) {
return "IE"
} //判断是否IE浏览器
}
var mb = myBrowser()
if ("IE" == mb) {
alert("我是 IE")
}
if ("FF" == mb) {
alert("我是 Firefox")
}
if ("Chrome" == mb) {
alert("我是 Chrome")
}
if ("Opera" == mb) {
alert("我是 Opera")
}
if ("Safari" == mb) {
alert("我是 Safari")
}
主要用到navigator.userAgent代码如下:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<script type="text/javascript">
function myBrowser(){
var userAgent = navigator.userAgent//取得浏览器的userAgent字符串
console.log(userAgent)
var isOpera = userAgent.indexOf("Opera") >-1
if (isOpera) {
return "Opera"
}//判断是否Opera浏览器
if (userAgent.indexOf("Firefox") >-1) {
return "FF"
} //判断是否Firefox浏览器
if (userAgent.indexOf("Chrome") >-1){
return "Chrome"
}
if (userAgent.indexOf("compatible") >-1 &&userAgent.indexOf("MSIE") >-1 &&!isOpera) {
return "IE"
}//判断是否IE浏览器
}
var cc = myBrowser()
if(cc == "Chrome"){
alert("当前是Chrome浏览器")
}
if(cc == "IE"){
alert("当前是IE浏览器")
}
</script>
</body>
</html>
var browser = getBrowserInfo() //浏览器信息//alert(browser)//IE 11.0
//IE11以下: MSIE 10.0、MSIE9.0等
//chrome:chrome/41.0.2272.89 [返回的是个数组]
//firefox: firefox/42.0 [返回的是个数组]
var verinfo = (browser+"").replace(/[^0-9.]/ig,"")//浏览器版本
//alert(verinfo)//11.0
//IE浏览器: 11.0/10.0/9.0
//chrome浏览器:41.0.2272.89
//Firefox浏览器: 42.0
function getBrowserInfo()
{
var agent = navigator.userAgent.toLowerCase()
//console.log(agent)
//agent chrome : mozilla/5.0 (windows nt 6.1wow64) applewebkit/537.36 (khtml, like gecko) chrome/41.0.2272.89 safari/537.36
//agent firefox : mozilla/5.0 (windows nt 6.1wow64rv:42.0) gecko/20100101 firefox/42.0
//agent IE11: mozilla/5.0 (windows nt 6.1wow64trident/7.0slcc2.net clr 2.0.50727.net clr 3.5.30729
//接上.net clr 3.0.30729media center pc 6.0infopath.2.net4.0c.net4.0erv:11.0) like gecko
(可以看出IE11中不包括MSIE字段)
//agent IE10: mozilla/5.0(compatiblemsie 10.0windows nt 6.1wow64trident/6.0)
var regStr_ie = /msie [\d.]+/gi
var regStr_ff = /firefox\/[\d.]+/gi
var regStr_chrome = /chrome\/[\d.]+/gi
var regStr_saf = /safari\/[\d.]+/gi
//IE11以下
if(agent.indexOf("msie") >0)
{
return agent.match(regStr_ie)
}
//IE11版本中不包括MSIE字段
if(agent.indexOf("trident") >0&&agent.indexOf("rv") >0){
return "IE " + agent.match(/rv:(\d+\.\d+)/) [1]
}
//firefox
if(agent.indexOf("firefox") >0)
{
return agent.match(regStr_ff)
}
//Chrome
if(agent.indexOf("chrome") >0)
{
return agent.match(regStr_chrome)
}
//Safari
if(agent.indexOf("safari") >0 &&agent.indexOf("chrome") <0)
{
return agent.match(regStr_saf)
}
}