DIV CSS 佈局教程網

JS 判斷瀏覽器類型與版本:常用寫法與 navigator 資訊
編輯:關於JavaScript     

瀏覽器品牌繁多、標準不一,同一個功能常需要分版本處理。以下整理最常被用到的判斷手法,以及 navigator 上可取得的各項資訊。

一、判斷是否為 IE

document.all ? 'IE' : 'others';
// IE 下 document.all 有值,其他瀏覽器則否

navigator.userAgent.indexOf("MSIE") > 0 ? 'IE' : 'others';
// userAgent 描述使用者代理資訊

navigator.appName.indexOf("Microsoft") != -1 ? 'IE' : 'others';
// appName 描述瀏覽器名稱

二、判斷 IE 版本

// 已知是 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 上可取得的資訊

  • navigator.appCodeName:瀏覽器程式碼名稱
  • navigator.appName:瀏覽器名稱
  • navigator.appVersion:瀏覽器版本號
  • navigator.javaEnabled():是否支援 Java
  • navigator.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 需要繞過時。

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