前端开发中,经常会出现对不同浏览器内核使用不同的方式处理问题,以达到兼容性更好的目的,那就涉及到判断当前浏览器使用的内核。这里使用 navigator.userAgent 判断当前浏览器内核。
代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>使用 navigator.userAgent 判断当前浏览器内核</title>
</head>
<body>
<script>
/***
* navigator.userAgent
谷歌
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.106 Safari/537.36"
火狐
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10.13; rv:70.0) Gecko/20100101 Firefox/70.0"
opera
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.132 Safari/537.36 OPR/63.0.3368.107 (Edition Baidu)"
safari
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/12.0.3 Safari/605.1.15"
IE
"Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; WOW64; Trident/7.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0)"
Edge
"Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; rv:11.0) like Gecko"
*/
function getCurrentBrowserType() {
var userAgent = navigator.userAgent; //取得浏览器的userAgent字符串
var isOpera = userAgent.indexOf("OPR") > -1;
// 判断是否Opera浏览器
if (isOpera) {
return "Opera"
}
// 判断是否Firefox浏览器
if (userAgent.indexOf("Firefox") > -1) {
return "FF";
}
// 判断是否Chrome浏览器
if (userAgent.indexOf("Chrome") > -1) {
return "Chrome";
}
// 判断是否Safari浏览器
if (userAgent.indexOf("Safari") > -1) {
return "Safari";
}
// 判断是否IE浏览器
if (userAgent.indexOf("compatible") > -1 && userAgent.indexOf("MSIE") > -1 && !isOpera) {
return "IE";
}
}
alert(getCurrentBrowserType());
</script>
</body>
</html>
发表评论: