首页 > web前端 > js教程 > 浏览器检测JS代码(兼容目前各大主流浏览器)_javascript技巧

浏览器检测JS代码(兼容目前各大主流浏览器)_javascript技巧

WBOY
发布: 2016-05-16 15:14:33
原创
1266 人浏览过

本文实例介绍了JS代码实现浏览器检测,分享给大家供大家参考,具体内容如下

var BrowserMatch = {
  init: function () {
    this.browser = this.getBrowser().browser || "An Unknown Browser";
    this.version = this.getBrowser().version || "An Unknown Version";
    this.OS = this.getOS() || "An Unknown OS";
  },
  getOS:function(){
    if(navigator.platform.indexOf("Win")!= -1) return "Windows";
    if(navigator.platform.indexOf("Mac")!= -1) return "Mac";
    if(navigator.platform.indexOf("Linux")!= -1) return "Linux";
    if(navigator.userAgent.indexOf("iPhone")!= -1) return "iPhone/iPod";
  },
  getBrowser:function () {
    var rMsie = /(msie\s|trident\/7)([\w\.]+)/;
    var rTrident = /(trident)\/([\w.]+)/;
    var rFirefox = /(firefox)\/([\w.]+)/; 
    var rOpera = /(opera).+version\/([\w.]+)/;
    var rNewOpera = /(opr)\/(.+)/;
    var rChrome = /(chrome)\/([\w.]+)/;
    var rSafari = /version\/([\w.]+).*(safari)/;
    var ua = navigator.userAgent.toLowerCase();
    var matchBS,matchBS2;
    matchBS = rMsie.exec(ua);
    if (matchBS != null) {
      matchBS2 = rTrident.exec(ua);
      if (matchBS2 != null){
        switch (matchBS2[2]){
          case "4.0": return { browser : "IE", version : "8" };break;
          case "5.0": return { browser : "IE", version : "9" };break;
          case "6.0": return { browser : "IE", version : "10" };break;
          case "7.0": return { browser : "IE", version : "11" };break;
          default:return { browser : "IE", version : "Undefined" };
        }
      }else{
        return {browser : "IE", version : matchBS[2] || "0" };
      }
    }
    matchBS = rFirefox.exec(ua);  
    if ((matchBS != null)&&(!(window.attachEvent))&&(!(window.chrome))&&(!(window.opera))) {  
      return { browser : matchBS[1] || "", version : matchBS[2] || "0" };
    }
    matchBS = rOpera.exec(ua);         
    if ((matchBS != null)&&(!(window.attachEvent))) {     
      return { browser : matchBS[1] || "", version : matchBS[2] || "0" };
    }
    matchBS = rChrome.exec(ua);  
    if ((matchBS != null)&&(!!(window.chrome))&&(!(window.attachEvent))) {
      matchBS2 = rNewOpera.exec(ua);       
      if(matchBS2 == null){
        return { browser : matchBS[1] || "", version : matchBS[2] || "0" };
      }else{
        return { browser : "Opera", version : matchBS2[2] || "0" };
      }  
    }
    matchBS = rSafari.exec(ua);          
    if ((matchBS != null)&&(!(window.attachEvent))&&(!(window.chrome))&&(!(window.opera))) {   
      return { browser : matchBS[2] || "", version : matchBS[1] || "0" };
    }           
  }
};  
BrowserMatch.init();
登录后复制

调用方法:(首先得引入js文件,大家应该都懂的)

获取浏览器名:BrowserMatch.browser;

获取浏览器版本:BrowserMatch.version;

获取所处操作系统:BrowserMatch.OS;

以上就是本文的全部内容,希望对大家的学习有所帮助。

相关标签:
来源:php.cn
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板