DIV CSS 佈局教程網

用 navigator 判斷客戶端作業系統:platform 與 userAgent 的實作
編輯:關於JavaScript     

實作程式碼

 <!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>js 判斷客戶端操作系統類型</title>
</head>
<body>
<script>
function detectOS() {
  var sUserAgent = navigator.userAgent;

  var isWin = (navigator.platform == "Win32") || (navigator.platform == "Windows");
  var isMac = (navigator.platform == "Mac68K") || (navigator.platform == "MacPPC") ||
              (navigator.platform == "Macintosh") || (navigator.platform == "MacIntel");

  if (isMac) return "MacOS";

  var isUnix = (navigator.platform == "X11") && !isWin && !isMac;
  if (isUnix) return "Unix";

  var isLinux = (String(navigator.platform).indexOf("Linux") > -1);
  if (isLinux) return "Linux";

  if (isWin) {
    var isWin2K = sUserAgent.indexOf("Windows NT 5.0") > -1 || sUserAgent.indexOf("Windows 2000") > -1;
    if (isWin2K) return "Windows2000";

    var isWinXP = sUserAgent.indexOf("Windows NT 5.1") > -1 || sUserAgent.indexOf("Windows XP") > -1;
    if (isWinXP) return "WindowsXP";

    var isWin2003 = sUserAgent.indexOf("Windows NT 5.2") > -1 || sUserAgent.indexOf("Windows 2003") > -1;
    if (isWin2003) return "Windows2003";

    var isWinVista = sUserAgent.indexOf("Windows NT 6.0") > -1 || sUserAgent.indexOf("Windows Vista") > -1;
    if (isWinVista) return "Windows Vista";

    var isWin7 = sUserAgent.indexOf("Windows NT 6.1") > -1 || sUserAgent.indexOf("Windows 7") > -1;
    if (isWin7) return "Windows7";
  }

  return "other";
}

document.writeln("您的操作系統是:" + detectOS());
</script>
</body>
</html>

程式在判斷什麼

策略是兩段式:先用 navigator.platform 判斷大類(Mac、Unix、Linux、Windows),若落在 Windows 再深入 userAgent 的字串比對,靠 Windows NT x.x 這個版本號對應到家用名稱。

對照表大致是:NT 5.0 是 2000、5.1 是 XP、5.2 是 2003、6.0 是 Vista、6.1 是 7。每個判斷都同時檢查 NT 碼與中文/英文名稱,是為了應對不同語言版本的 UA 差異。

這份程式已經過時了

有幾個問題必須指出。

版本覆蓋嚴重不足。Windows 8 是 NT 6.2、8.1 是 6.3、10 與 11 都是 NT 10.0,全都會落到 "other"。Mac 也早已不是 MacPPC 時代,Apple Silicon 上 platform 回報的是 MacIntel。

navigator.platform 已棄用。現代做法是改用 navigator.userAgentData?.platform(Client Hints),並保留 navigator.platform 作為退路。

UA 字串可被偽造,也不穩定。基於 UA 的判斷本質上是猜測。若目的是效能調校或分支邏輯,請改用特性偵測——直接問「這個 API 在不在」,而不是問「你是什麼系統」。

document.writeln 不該用在載入後。它會清空整個文件。範例因為寫在頁面載入期間所以沒事,但這是個容易誤用的 API,改用 document.body.textContent = ... 更安全。

如果只需要一個粗略判斷

 function detectOS() {
  var ua = navigator.userAgent;
  var platform = navigator.userAgentData?.platform || navigator.platform || '';

  if (/android/i.test(ua)) return "Android";
  if (/iPad|iPhone|iPod/.test(ua) || (platform === 'MacIntel' && navigator.maxTouchPoints > 1)) return "iOS";
  if (/Win/i.test(platform)) return "Windows";
  if (/Mac/i.test(platform)) return "macOS";
  if (/Linux/i.test(platform)) return "Linux";
  return "unknown";
}

這版的用意不是精確辨識版本號,而是回答「要不要給觸控友善的介面」「要不要載入某個平台的安裝說明」這類問題。多數情境下,這樣的粒度已經足夠,而且不會因為作業系統出新版就失效。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved