瀏覽器端判斷當前設備的運行環境

瀏覽器端判斷當前設備的運行環境

可判斷環境:

  • 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/

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章