浏览器端判断当前设备的运行环境

浏览器端判断当前设备的运行环境

可判断环境:

  • android
  • iOS
  • weixin
  • Linux
  • windows
  • IE
  • Mac

直接先上代码:

let device = function(t) {
    
    
    let userAgent = navigator.userAgent.toLowerCase();
    let n = function(e) {
    
    
        let t = new RegExp(e + "/([^\\s\\_\\-]+)");
        return e = (userAgent.match(t) || [])[1],
        e || !1
    }
    let r = {
    
    
        os: function() {
    
    
            if(/windows/.test(userAgent)){
    
    
                return "windows";
            }else{
    
    
                if(/linux/.test(userAgent)){
    
    
                    return "linux";
                }else{
    
    
                    if(/iphone|ipod|ipad|ios/.test(userAgent)){
    
    
                        return "ios";
                    }else{
    
    
                        if(/mac/.test(userAgent)){
    
    
                            return "mac";
                        }
                    }
                }
            }
            return void 0;
        }(),
        ie: function() {
    
    
            return !!(window.ActiveXObject || "ActiveXObject" in window) && ((userAgent.match(/msie\s(\d+)/) || [])[1] || "11")
        }(),
        weixin: n("micromessenger")
    };
    r.android = /android/.test(userAgent);
    r.ios = "ios" === r.os;
    return r;
}

返回结果:
在这里插入图片描述
有时你的 App 可能会对 userAgent 插入一段特定的标识,譬如:

Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.143 myapp/1.8.6 Safari/537.36

你要验证当前的 WebView 是否在你的 App 环境,即可通过上述的myapp(即为 Native 给 Webview 插入的标识,可以随意定义)来判断。

var device = device('myapp');
if(device.myapp){
    
    
  alert('在我的App环境');
}   

这里借鉴于layuidevice判断方法,如果使用了layui的框架,可以直接使用layui.device()方法来获取,如果没有可以学习下贤心大神的写法。

Tips: layui是贤心大神的作品,大家可以去膜拜一下,https://www.layui.com/

猜你喜欢

转载自blog.csdn.net/zy1281539626/article/details/112153207
今日推荐