如何經過JS來判斷打開的瀏覽器頁面是PC端仍是移動端或者是其餘形式(navigator.userAgent)

在進行渠道管理時,因爲要在各類不一樣端(包括任何形式的pc端、移動端、app、Android/IOS、小程序等)中內嵌h5頁面來展現不一樣的內容,且具備良好的兼容性。使用navigator.userAgent 能夠實現該功能,且在全部瀏覽器都支持。javascript

一句就能夠判斷是什麼端?

window.location.href = /Android|webOS|iPhone|iPod|BlackBerry/i.test(navigator.userAgent) 
? "mobile_web端頁面" 
: "PC端頁面"
// 經過正則來判斷
// 若是是手機端跳轉到 mobile_web端頁面
// 若是是PC端跳轉到 PC端頁面
複製代碼

一.navigator.userAgent 使用

瀏覽器用於 HTTP 請求的用戶代理頭的值,經過UserAgent能夠取得瀏覽器類別、版本,客戶端操做系統等信息。java

  • 在PC端打開 ,navigator.userAgent 顯示以下
Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36
複製代碼
  • 在手機web端打開 ,navigator.userAgent 顯示以下
Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/11.0 Mobile/15A372 Safari/604.1
複製代碼

二.navigator.userAgent 應用場景

1. 判斷頁面是在手機端仍是PC端打開

<script>
  console.log(navigator.userAgent);
  window.location.href = /Android|webOS|iPhone|iPod|BlackBerry/i.test(navigator.userAgent)
  ? "http://localhost:8888/mobile_web"
  : "http://localhost:8888/PC";
</script>
複製代碼

2. 判斷頁面是在手機端,平板端仍是PC端打開

<script>
  console.log(navigator.userAgent);
  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
    };
}();

if (os.isAndroid || os.isPhone) {
  console.log("手機")
} else if (os.isTablet) {
  console.log("平板")
} else if(os.isPc) {
  console.log("電腦")
}
</script>
複製代碼

3. 獲取手機操做系統類型,判斷是Android或者IOS

/** * 獲取操做系統類型, * 0 -- Android * 1 -- iOS */
 function getOSType() {
     if (/(Android)/i.test(navigator.userAgent)) {
         return 0;
     } else if (/(iPhone|iPad|iPod|iOS)/i.test(navigator.userAgent)) {
         return 1;
     } else {
         return 2;
     }
 }
複製代碼

4. 判斷當前環境是不是微信環境

function is_weixin(){
      var ua = navigator.userAgent.toLowerCase();
      if(ua.match(/MicroMessenger/i) == "micromessenger") {
           return true;
      } else {
            return false;
      }
}
複製代碼

到這裏就能夠輕鬆實現上面的問題,能夠在不一樣端獲取瀏覽器信息,以此來展現不一樣的頁面內容。 固然,無論是在Vue中仍是React中,均可以輕鬆拿到。web

相關文章
相關標籤/搜索