JavaScript 判斷方案
1. navigator.userAgent 解析(傳統)
const ua = navigator.userAgent.toLowerCase();
const browser = {
// 引擎
trident: ua.indexOf('trident') > -1, // IE 內核
presto: ua.indexOf('presto') > -1, // Opera 舊內核
webkit: ua.indexOf('applewebkit') > -1, // WebKit 內核
gecko: ua.indexOf('gecko') > -1 && ua.indexOf('khtml') === -1, // Firefox 內核
// 瀏覽器
ie: ua.indexOf('msie') > -1 || ua.indexOf('trident') > -1,
edge: ua.indexOf('edge') > -1,
chrome: ua.indexOf('chrome') > -1 && ua.indexOf('edge') === -1,
firefox: ua.indexOf('firefox') > -1,
safari: ua.indexOf('safari') > -1 && ua.indexOf('chrome') === -1,
opera: ua.indexOf('opera') > -1 || ua.indexOf('opr') > -1,
// 設備
mobile: /mobile|android|iphone|ipad/.test(ua),
ios: /iphone|ipad|ipod/.test(ua),
android: ua.indexOf('android') > -1,
wechat: ua.indexOf('micromessenger') > -1,
// 版本提取
getVersion: function() {
const patterns = {
ie: /(?:msie |rv:)(\d+)/,
edge: /edge\/(\d+)/,
chrome: /chrome\/(\d+)/,
firefox: /firefox\/(\d+)/,
safari: /version\/(\d+)/
};
for (const [key, regex] of Object.entries(patterns)) {
if (this[key]) {
const match = ua.match(regex);
if (match) return parseInt(match[1], 10);
}
}
return null;
}
};
console.log(browser); // { ie: false, chrome: true, version: 120, ... }
2. 特性檢測(現代推薦)
// 檢測功能而非瀏覽器
const features = {
fetch: 'fetch' in window,
promise: 'Promise' in window,
arrowFunction: (() => { try { eval('()=>{}'); return true; } catch(e) { return false; } })(),
webgl: !!document.createElement('canvas').getContext('webgl'),
serviceWorker: 'serviceWorker' in navigator,
intersectionObserver: 'IntersectionObserver' in window
};
// 使用
if (features.fetch) { /* 使用 fetch */ }
else { /* Polyfill 或降級 */ }
HTML 條件註釋(僅 IE 5-9 支援,IE10+ 已移除)
| 語法 | 匹配瀏覽器 | 示例 |
<!--[if IE]>...<![endif]--> | 所有 IE | 引入 IE 專用 Polyfill |
<!--[if IE 8]>...<![endif]--> | 僅 IE8 | 修復 IE8 特定 Bug |
<!--[if gt IE 8]>...<![endif]--> | IE9+ | 現代代碼 |
<!--[if lt IE 9]>...<![endif]--> | IE8 及以下 | ES5 Shim、HTML5 Shiv |
<!--[if !IE]><!-->...<!--<![endif]--> | 非 IE | 現代瀏覽器專用代碼 |
現代最佳實踐
- 優先特性檢測:用
'feature' in window 替代 UA 判斷
- Polyfill 按需加載:使用
polyfill.io 或 core-js 配合 bundler
- 避免 UA 嗅探:UA 可偽造、變化快、維護成本高
- 漸進增強:基礎功能無 JS 可用,高級功能特性檢測後增強
工具庫推薦