瀏覽器偵測曾是前端相容性處理的核心手段,但現代開發已轉向功能偵測。本文詳細解析 User-Agent 解析實作細節、各瀏覽器 UA 特徵、已知坑點,並推薦現代最佳實踐方案。
// Chrome (Windows)
Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36
// Firefox (Windows)
Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:121.0) Gecko/20100101 Firefox/121.0
// Safari (macOS)
Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.1 Safari/605.1.15
// Edge (Chromium)
Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36 Edg/120.0.0.0
// IE 11
Mozilla/5.0 (Windows NT 10.0; WOW64; Trident/7.0; rv:11.0) like Gecko
// 微信內建瀏覽器
Mozilla/5.0 (iPhone; CPU iPhone OS 17_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148 MicroMessenger/8.0.44(0x18002c2a) NetType/WIFI Language/zh_CN
;(function($, window, document, undefined) {
if (!window.browser) {
var userAgent = navigator.userAgent.toLowerCase();
var uaMatch;
window.browser = {};
// IE 偵測 (最優先,因為 UA 偽裝最多)
function isIE() {
return 'ActiveXObject' in window ||
('msie' in userAgent) ||
('trident' in userAgent);
}
// 版本提取通用函式
function extractVersion(ua, regex) {
var match = ua.match(regex);
return match ? match[1] : null;
}
// 按優先級順序偵測 (Edge 必須在 Chrome 前)
// 1. Edge (Chromium)
uaMatch = extractVersion(userAgent, /edg\/([\d.]+)/);
if (uaMatch) {
window.browser.name = 'edge';
window.browser.version = uaMatch;
}
// 2. Chrome (排除 Edge/Opera/Brave 等 Chromium 系)
else if (!uaMatch && /chrome/.test(userAgent) && !/edg|opr|brave|vivaldi/.test(userAgent)) {
uaMatch = extractVersion(userAgent, /chrome\/([\d.]+)/);
window.browser.name = 'chrome';
window.browser.version = uaMatch;
}
// 3. Firefox
else if (!uaMatch && /firefox/.test(userAgent)) {
uaMatch = extractVersion(userAgent, /firefox\/([\d.]+)/);
window.browser.name = 'firefox';
window.browser.version = uaMatch;
}
// 4. Safari (需在 Chrome 後,因 Chrome UA 含 Safari)
else if (!uaMatch && /safari/.test(userAgent) && !/chrome|crios/.test(userAgent)) {
uaMatch = extractVersion(userAgent, /version\/([\d.]+)/);
window.browser.name = 'safari';
window.browser.version = uaMatch;
}
// 5. Opera
else if (!uaMatch && /opr|opera/.test(userAgent)) {
uaMatch = extractVersion(userAgent, /(?:opr|opera)\/([\d.]+)/);
window.browser.name = 'opera';
window.browser.version = uaMatch;
}
// 6. IE 10/11 (Trident 引擎)
else if (!uaMatch && isIE()) {
if (/msie ([\d.]+)/.test(userAgent)) {
// IE 10 及以下
window.browser.name = 'ie';
window.browser.version = RegExp.$1;
} else if (/trident\/7/.test(userAgent) || /rv:11/.test(userAgent)) {
// IE 11
window.browser.name = 'ie';
window.browser.version = '11';
} else {
window.browser.name = 'ie';
window.browser.version = 'unknown';
}
}
// 7. 其他/未知
else {
window.browser.name = 'unknown';
window.browser.version = '0';
}
// 作業系統偵測
window.browser.os = (function() {
if (/windows nt 10/.test(userAgent)) return 'windows 10/11';
if (/windows nt 6.3/.test(userAgent)) return 'windows 8.1';
if (/windows nt 6.2/.test(userAgent)) return 'windows 8';
if (/windows nt 6.1/.test(userAgent)) return 'windows 7';
if (/mac os x ([\d_]+)/.test(userAgent)) return 'macos ' + RegExp.$1.replace(/_/g, '.');
if (/iphone|ipad|ipod/.test(userAgent)) return 'ios';
if (/android ([\d.]+)/.test(userAgent)) return 'android ' + RegExp.$1;
if (/linux/.test(userAgent)) return 'linux';
return 'unknown';
})();
// 裝置類型
window.browser.device = /mobile|android|iphone|ipad|ipod/.test(userAgent) ? 'mobile' : 'desktop';
// jQuery 擴充方法 (若專案使用 jQuery)
if ($ && !$.browser) {
$.browser = window.browser;
$.each(['ie', 'chrome', 'firefox', 'safari', 'opera', 'edge'], function(i, name) {
$['is' + name.charAt(0).toUpperCase() + name.slice(1)] = function() {
return window.browser.name === name;
};
});
}
}
})(window.jQuery || {}, window, document);
| 坑點 | 說明 | 影響 |
|---|---|---|
| UA 可被偽造 | 使用者/擴充套件/開發工具可任意修改 | 不可用於安全驗證 |
| Chromium 系 UA 高度相似 | Chrome/Edge/Opera/Brave/Vivaldi 核心相同 | 需檢查特定關鍵字 (Edg, OPR 等) |
| Chrome 100+ 版本號位數變化 | 兩位數→三位數,正則需支援 \d+ | 版本解析失敗 |
| iOS 所有瀏覽器皆為 WebKit | Chrome/Firefox iOS 版實際是 Safari 套殼 | 功能偵測比 UA 更準確 |
| User-Agent Client Hints 取代趨勢 | Chrome 逐步凍結 UA,改用 Sec-CH-UA 標頭 | 伺服器端需遷移 |
// ❌ 錯誤:根據瀏覽器分派代碼
if (browser.name === 'ie') { polyfill(); }
// ✅ 正確:檢測功能是否存在
if (!Element.prototype.closest) { polyfill(); }
if (!Array.prototype.includes) { polyfill(); }
// ✅ 正確:CSS @supports 查詢
@supports (display: grid) { .layout { display: grid; } }
// ✅ 正確:現代 Polyfill 策略 (core-js)
import 'core-js/stable';
import 'regenerator-runtime/runtime';
// 配合 browserslist + babel/preset-env 自動按目標環境注入
// 伺服器端讀取標頭
// Sec-CH-UA: "Google Chrome";v="120", "Chromium";v="120", "Not_A Brand";v="24"
// Sec-CH-UA-Mobile: ?0
// Sec-CH-UA-Platform: "Windows"
// Sec-CH-UA-Platform-Version: "15.0.0"
// 前端 JavaScript 存取 (需 HTTPS + 權限政策)
navigator.userAgentData?.getHighEntropyValues(['platform', 'platformVersion', 'architecture', 'bitness', 'model', 'formFactor'])
.then(data => console.log(data));
// { platform: "Windows", platformVersion: "15.0.0", architecture: "x86", ... }
interface BrowserInfo {
name: 'chrome' | 'firefox' | 'safari' | 'edge' | 'opera' | 'ie' | 'unknown';
version: string;
os: string;
device: 'mobile' | 'desktop' | 'tablet';
engine: 'webkit' | 'gecko' | 'blink' | 'trident' | 'unknown';
}
declare global {
interface Window {
browser: BrowserInfo;
}
interface JQueryStatic {
browser: BrowserInfo;
isIE(): boolean;
isChrome(): boolean;
isFirefox(): boolean;
isSafari(): boolean;
isOpera(): boolean;
isEdge(): boolean;
}
}