萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

jQuery 檢測用戶作業系統 (Mac/PC) 並動態加載樣式:User-Agent 解析與現代替代方案

原始實現

if (navigator.userAgent.indexOf('Mac OS X') !== -1) {
    $("body").addClass("mac");
} else {
    $("body").addClass("pc");
}

User-Agent 解析深度分析

典型 UA 字符串

// macOS Chrome
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36"

// Windows 10 Chrome
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36"

// iPhone (常被誤判為 Mac)
"Mozilla/5.0 (iPhone; CPU iPhone OS 17_2 like Mac OS X) AppleWebKit/605.1.15..."

// iPad (iPadOS 13+ 默認桌面模式,UA 類似 Mac)
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15) AppleWebKit/605.1.15..."

原文邏輯缺陷

  • 誤判 iOS 設備:iPhone/iPad UA 含 "Mac OS X",會被判為 Mac
  • 無法識別 Linux:非 Mac 統一歸為 PC,Linux 用戶體驗受影響
  • UA 可偽造:用戶可修改 UA,不可作為安全依據
  • 維護成本高:新系統發布需更新匹配規則

改進版:精確平台檢測

function getPlatform() {
    const ua = navigator.userAgent;
    const platform = navigator.platform; // 更可靠:Win32, MacIntel, Linux x86_64 等
    
    // 1. 優先檢查 platform (較難偽造)
    if (platform === 'MacIntel' || platform === 'MacPPC' || platform === 'Mac68K') {
        // 2. 排除 iPad (iPadOS 13+ platform 也是 MacIntel)
        if (!/iPad|iPhone|iPod/.test(ua)) return 'mac';
    }
    
    if (platform === 'Win32' || platform === 'Win64') return 'windows';
    if (platform.startsWith('Linux')) return 'linux';
    
    // 3. 回退 UA 關鍵詞
    if (/Windows/.test(ua)) return 'windows';
    if (/Mac OS X/.test(ua) && !/iPhone|iPad|iPod/.test(ua)) return 'mac';
    if (/Linux/.test(ua)) return 'linux';
    if (/Android/.test(ua)) return 'android';
    if (/iPhone|iPad|iPod/.test(ua)) return 'ios';
    
    return 'unknown';
}

// 使用
const platform = getPlatform();
document.body.classList.add(platform); // mac, windows, linux, ios, android...

現代最佳方案:Client Hints API (Chrome 89+)

// 安全、標準化、用戶可控的設備信息獲取
async function getPlatformModern() {
    // 需在 HTTPS 且有權限策略
    if (!navigator.userAgentData) return getPlatform(); // 降級
    
    const {platform, mobile} = navigator.userAgentData;
    // platform: "macOS", "Windows", "Linux", "Android", "iOS"
    // mobile: boolean
    
    if (mobile) return platform.toLowerCase(); // android, iOS
    return platform.toLowerCase(); // macos, windows, linux
}

// 使用
getPlatformModern().then(p => document.body.classList.add(p));

CSS 條件樣式應用

<style>
/* Mac 風格:圓角、陰影、字體 */
body.mac .btn { border-radius: 8px; font-family: -apple-system, BlinkMacSystemFont; }
body.mac .modal { backdrop-filter: blur(20px); }

/* Windows 風格:銳利邊角、Segoe UI */
body.windows .btn { border-radius: 4px; font-family: 'Segoe UI', system-ui; }

/* Linux 風格 */
body.linux .btn { border-radius: 4px; font-family: 'Noto Sans', system-ui; }

/* 觸摸設備優化 */
body.ios .btn, body.android .btn { 
    min-height: 44px; /* 觸控目標最小尺寸 */
    font-size: 16px;  /* 防止 iOS 雙擊縮放 */
}
</style>

實戰應用場景

1. 字體優化

// 系統字體棧 (System UI Font Stack)
const fontStack = {
    mac: '-apple-system, BlinkMacSystemFont, "PingFang SC", "Hiragino Sans GB"',
    windows: '"Segoe UI", "Microsoft YaHei", system-ui',
    linux: '"Noto Sans", "Source Han Sans", system-ui',
    fallback: 'system-ui, sans-serif'
};

document.body.style.fontFamily = fontStack[platform] || fontStack.fallback;

2. 快捷鍵提示差異化

const shortcuts = {
    mac: { save: '⌘+S', copy: '⌘+C', paste: '⌘+V', find: '⌘+F' },
    windows: { save: 'Ctrl+S', copy: 'Ctrl+C', paste: 'Ctrl+V', find: 'Ctrl+F' },
    linux: { save: 'Ctrl+S', copy: 'Ctrl+C', paste: 'Ctrl+V', find: 'Ctrl+F' }
};

function renderShortcut(action) {
    return shortcuts[platform]?.[action] || shortcuts.windows[action];
}

3. 滾動條/交互行為適配

// Mac 隱藏滾動條,Windows 永遠顯示
if (platform === 'mac') {
    document.documentElement.style.setProperty('--scrollbar-width', '0');
} else {
    document.documentElement.style.setProperty('--scrollbar-width', 'auto');
}

React/Vue 框架集成

{/* React Hook */}
function usePlatform() {
    const [platform, setPlatform] = useState('unknown');
    useEffect(() => {
        setPlatform(getPlatform());
    }, []);
    return platform;
}

// 組件中
function App() {
    const platform = usePlatform();
    return ...;
}

總結

檢測作業系統應用於**體驗優化**(字體、快捷鍵、交互細節),而非功能邏輯分支。現代方案優先級:**Client Hints API > navigator.platform + UA 輔助 > 單純 UA 匹配**。切記:UA 可偽造,切勿用於權限控制或安全判斷。

copyright © 萬盛學電腦網 all rights reserved