项目需求:
由于客户使用的浏览器版本不同,在项目中使用了Vue和ES6等较新的框架和语法时,就会导致网站不能正常打开,因此需要增加浏览器版本提示,并建议用户使用适配版本。
下午在各大网站上搜索一圈代码后,整理出一版可使用的JS程序,方便参考,以节省下次使用时间。
<script type="text/javascript">
// var chars=navigator.userAgent; //浏览器的用户代理字符串
var ua = navigator.userAgent;
ua = ua.toLowerCase();
console.log('ua',ua)
// 使用谷歌浏览器时,打印出来是这样:(index):268 ua mozilla/5.0 (windows nt 10.0; win64; x64) applewebkit/537.36 (khtml, like gecko) chrome/87.0.4280.88 safari/537.36
var match = /(webkit)[ \/]([\w.]+)/.exec(ua) ||
/(opera)(?:.*version)?[ \/]([\w.]+)/.exec(ua) ||
/(msie) ([\w.]+)/.exec(ua) ||
!/compatible/.test(ua) && /(mozilla)(?:.*? rv:([\w.]+))?/.exec(ua) || [];
console.log('match',match)
// match 打印结果:Array(3)0: "webkit/537.36"1: "webkit"2: "537.36"groups: undefinedindex: 47input: "mozilla/5.0 (windows nt 10.0; win64; x64) applewebkit/537.36 (khtml, like gecko) chrome/87.0.4280.88 safari/537.36"length: 3__proto__: Array(0)
//如果需要获取浏览器版本号:match[2]
switch(match[1]){
case "msie": //ie
if (parseInt(match[2]) === 6){ //ie6
alert("ie6");
alert("暂时不支持IE7.0及以下版本浏览器,请升级您的浏览器版本!");
}
else if (parseInt(match[2]) === 7) { //ie7
alert("ie7");
}
else if (parseInt(match[2]) === 8){ //ie8
alert("ie8");
}
else if(parseInt(match[2]) === 9){
alert("ie9");
}
break;
case "webkit": //safari or chrome
alert("safari or chrome");
break;
case "opera": //opera
alert("opera");
break;
case "mozilla": //Firefox
alert("Firefox");
break;
default:
break;
}
</script>