JS获取浏览器的类型和版本号

1,820 阅读1分钟

userAgent 属性是一个只读的字符串,例如:'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/106.0.0.0 Safari/537.36'

获取浏览器的版本号

function getBrowserVersion(){
     var Sys = {}; 
     var ua = navigator.userAgent.toLowerCase(); 
     var s; 
     (s = ua.match(/rv:([\d.]+)\) like gecko/)) ? Sys.ie = s[1] :
     (s = ua.match(/msie ([\d\.]+)/)) ? Sys.ie = s[1] : 
     (s = ua.match(/edge\/([\d\.]+)/)) ? Sys.edge = s[1] :
     (s = ua.match(/firefox\/([\d\.]+)/)) ? Sys.firefox = s[1] : 
     (s = ua.match(/(?:opera|opr).([\d\.]+)/)) ? Sys.opera = s[1] : 
     (s = ua.match(/chrome\/([\d\.]+)/)) ? Sys.chrome = s[1] : 
     (s = ua.match(/version\/([\d\.]+).*safari/)) ? Sys.safari = s[1] : 0; 
      // 根据关系进行判断
     if (Sys.ie) return ('IE: ' + Sys.ie); 
     if (Sys.edge) return ('EDGE: ' + Sys.edge);
     if (Sys.firefox) return ('Firefox: ' + Sys.firefox); 
     if (Sys.chrome) return ('Chrome: ' + Sys.chrome); 
     if (Sys.opera) return ('Opera: ' + Sys.opera); 
     if (Sys.safari) return ('Safari: ' + Sys.safari);
     return 'Unkonwn';
}

获取浏览器的类型

function getBrowserName(){
   var userAgent = navigator.userAgent;
   if(userAgent.indexOf("Opera") > -1 || userAgent.indexOf("OPR") > -1){
     return 'Opera';
   }
   else if(userAgent.indexOf("compatible") > -1 && userAgent.indexOf("MSIE") > -1){
     return 'IE';
   }
   else if(userAgent.indexOf("Edge") > -1){
      return 'Edge';
   }
   else if(userAgent.indexOf("Firefox") > -1){
      return 'Firefox';
   }
   else if(userAgent.indexOf("Safari") > -1 && userAgent.indexOf("Chrome") == -1){
     return 'Safari';
   }
   else if(userAgent.indexOf("Chrome") > -1 && userAgent.indexOf("Safari") > -1){
      return 'Chrome';
   }
   else if(!!window.ActiveXObject || "ActiveXObject" in window){
      return 'IE>=11';
   }
   else{
    return 'Unkonwn';
   }
}

判断IE版本

<!--[if IE 8]>仅IE8可识别<![endif]-->
<!--[if lte IE 8]> IE8及其以下版本可识别<![endif]-->
<!--[if lt IE 8]> IE8以下版本可识别<![endif]-->
<!--[if gte IE 8]> IE8及其以上版本可识别<![endif]-->
<!--[if gt IE 8]> IE8以上版本可识别<![endif]-->
<!--[if IE]> 所有的IE可识别<![endif]-->
<style>  
    #no-ie {  
        display: none;  
    }  
</style>  
<!--[if lt IE 8]>  
    <style>  
        #no-ie {  
            display: block;  
        }  
    </style>  
<![endif]-->  
<body>  
    <div id="no-ie">IE版本太低</div>  
</body>