瀏覽器品牌繁多、標準不一,同一個功能常需要分版本處理。以下整理最常被用到的判斷手法,以及 navigator 上可取得的各項資訊。
document.all ? 'IE' : 'others';
// IE 下 document.all 有值,其他瀏覽器則否
navigator.userAgent.indexOf("MSIE") > 0 ? 'IE' : 'others';
// userAgent 描述使用者代理資訊
navigator.appName.indexOf("Microsoft") != -1 ? 'IE' : 'others';
// appName 描述瀏覽器名稱
// 已知是 IE 的前提下
navigator.appVersion.match(/6./i) == "6." ? 'IE6' : 'other';
navigator.userAgent.indexOf("MSIE 6.0") > 0 ? 'IE6' : 'other';
navigator.appVersion.match(/7./i) == "7." ? 'IE7' : 'other';
navigator.userAgent.indexOf("MSIE 7.0") > 0 ? 'IE7' : 'other';
navigator.appVersion.match(/8./i) == "8." ? 'IE8' : 'other';
navigator.userAgent.indexOf("MSIE 8.0") > 0 ? 'IE8' : 'other';
IE11 之後 userAgent 中不再出現 MSIE,改為 Trident/7.0 搭配 rv:11.0,判斷時需要另外處理。
navigator.appCodeName:瀏覽器程式碼名稱navigator.appName:瀏覽器名稱navigator.appVersion:瀏覽器版本號navigator.javaEnabled():是否支援 Javanavigator.mimeTypes:MIME 類型陣列navigator.platform:執行平台navigator.plugins:外掛陣列navigator.userAgent:使用者代理字串UA 可以被偽造,版本判斷也繁瑣易碎,因此能用特性偵測就不要嗅探 UA。例如判斷是否支援某 API:
if (document.querySelectorAll) { /* 支援 */ }
if (window.addEventListener) { /* 支援 */ }
if ('transform' in document.documentElement.style) { /* 支援 */ }
UA 判斷留給「確實只能依瀏覽器區分」的極少數場景,例如某個特定舊版本的已知 Bug 需要繞過時。