JS judge the browser environment (PC, mobile or wechat browser)

Time:2020-9-25

Today, I suddenly saw a good code to share with you and leave a note for myself. JS judges the browser environment as follows:

Method 1

//Judge browser functions
  function isMobile(){
    if(window.navigator.userAgent.match(/(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Windows Phone)/i)) {
      Return true; // mobile terminal
    }else{
      Return false; // PC
    }
  }

Method 2: this method is extracted from: im.qq.com

var os = function() { 
   var ua = navigator.userAgent, 
   isWindowsPhone = /(?:Windows Phone)/.test(ua), 
   isSymbian = /(?:SymbianOS)/.test(ua) || isWindowsPhone,  
   isAndroid = /(?:Android)/.test(ua),  
   isFireFox = /(?:Firefox)/.test(ua),  
   isChrome = /(?:Chrome|CriOS)/.test(ua), 
   isTablet = /(?:iPad|PlayBook)/.test(ua) || (isAndroid && !/(?:Mobile)/.test(ua)) || (isFireFox && /(?:Tablet)/.test(ua)), 
   isPhone = /(?:iPhone)/.test(ua) && !isTablet, 
   isPc = !isPhone && !isAndroid && !isSymbian; 
   return { 
     isTablet: isTablet, 
     isPhone: isPhone, 
     isAndroid : isAndroid, 
     isPc : isPc 
   }; 
}(); 
 
//How to use it 
if(os.isAndroid || os.isPhone){
alert("-----");
}

Judge whether it is a wechat client:


 var isWechart = function () {
    var rst = true
    if(window.navigator.userAgent.match(/(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Windows Phone)/i)){
      var ua = navigator.userAgent.toLowerCase();
      if (!(ua.match(/MicroMessenger/i) == "micromessenger")) {
        rst = false;
      }
    }else {
      rst = false;
    }
    return rst;
  }

Judge whether the wechat browser is a PC or a mobile phone, and whether the mobile terminal is a wechat browser or a non wechat browser

//Platforms, devices and operating systems  
     var system = { 
       win: false, 
       mac: false, 
       xll: false, 
       ipad: false 
     }; 
     //Detection platform  
     var p = navigator.platform; 
     system.win = p.indexOf("Win") == 0; 
     system.mac = p.indexOf("Mac") == 0; 
     system.x11 = (p == "X11") || (p.indexOf("Linux") == 0); 
     system.ipad = (navigator.userAgent.match(/iPad/i) != null) ? true : false; 
     //Jump statement, if it is a mobile phone access, it will automatically jump to wap.baidu.com page  
     if (system.win || system.mac || system.xll || system.ipad) { 
       Alert ("opened on the PC side");
     } else { 
       var ua = navigator.userAgent.toLowerCase();  
       if(ua.match(/MicroMessenger/i)=="micromessenger") {  
         Alert ("opened on wechat on the mobile phone"); 
       } else {  
         Alert ("opened on mobile phone but not on wechat"); 
       }  
     }

The above is the whole content of this article, I hope to help you in your study, and I hope you can support developeppaer more.