DIV CSS 佈局教程網

判斷瀏覽器內核與版本的五種方案完整整理
編輯:關於JavaScript     

瀏覽器 detection 是個永遠繞不開的話題。以下整理五種常見方案,並說明各自的適用邊界——以及為什麼它們在今天多數情況下都不再是首選。

一、透過 jQuery 判斷

<script type="text/javascript">
  $(function () {
    if ($.browser.msie && ($.browser.version == "7.0")) {
      $("#yourannet").css("margin-left", "10px");
    } // IE7
    else if ($.browser.msie && ($.browser.version == "6.0") && !$.support.style) {
      $("#yourannet").css("margin-left", "15px");
    } // IE6
    else if ($.browser.msie && ($.browser.version == "8.0")) {
      $("#yourannet").css("margin-left", "20px");
    } // IE8
    else if ($.browser.msie && ($.browser.version == "9.0")) {
      $("#yourannet").css("margin-left", "25px");
    } // IE9
    else if (window.navigator.userAgent.toLowerCase().indexOf("360se") >= 1) {
      $("#yourannet").css("margin-left", "30px");
    } // 360 瀏覽器
  });
</script>

這裡有個非常重要的前提必須說明:$.browser 已在 jQuery 1.9 中被正式移除。原因是使用者代理字串(userAgent)的判斷方式不可靠,容易誤判。上面的程式碼在現代 jQuery 版本下會直接丟出錯誤。

jQuery 使用正則表達式匹配 userAgent 來判斷瀏覽器種類與版本。在 $.browser 還存在的年代,寫法大致如下:

$(function () {
  if ($.browser.msie) {
    alert("this is msie");
  } else if ($.browser.safari) {
    alert("this is safari!");
  } else if ($.browser.mozilla) {
    alert("this is mozilla!");
  } else if ($.browser.opera) {
    alert("this is opera");
  } else {
    alert("i don't know!");
  }
});

二、自訂正則匹配 userAgent

若不使用 jQuery,可自行寫一組正則來區分 IE、Firefox、Opera、Chrome、Safari:

// browser check ----- start
var userAgent = navigator.userAgent,
    rMsie = /.*(msie) ([\w.]+).*/,
    rFirefox = /.*(firefox)\/([\w.]+).*/,
    rOpera = /(opera).+version\/([\w.]+)/,
    rChrome = /.*(chrome)\/([\w.]+).*/,
    rSafari = /.*version\/([\w.]+).*(safari).*/;

function uaMatch(ua) {
  var match = rMsie.exec(ua);
  if (match != null) {
    return { browser: match[1] || "", version: match[2] || "0" };
  }
  match = rFirefox.exec(ua);
  if (match != null) {
    return { browser: match[1] || "", version: match[2] || "0" };
  }
  match = rOpera.exec(ua);
  if (match != null) {
    return { browser: match[1] || "", version: match[2] || "0" };
  }
  match = rChrome.exec(ua);
  if (match != null) {
    return { browser: match[1] || "", version: match[2] || "0" };
  }
  match = rSafari.exec(ua);
  if (match != null) {
    return { browser: match[2] || "", version: match[1] || "0" };
  }
  return { browser: "", version: "0" };
}

var browserMatch = uaMatch(navigator.userAgent.toLowerCase());
if (browserMatch.browser) {
  myApp.browser = myApp.browser || {};
  myApp.browser[browserMatch.browser] = true;
  myApp.browserName = browserMatch.browser;
  myApp.browserVersion = browserMatch.version;
  myApp.browserLanguage = navigator.language || navigator.userLanguage || "";
}
// browser check ----- end

使用方式:

myApp.browser.msie        // 是否為 IE
myApp.browserName         // 瀏覽器名稱
myApp.browserVersion      // 瀏覽器版本
myApp.browserLanguage     // 語言

要注意匹配順序很重要:Chrome 的 userAgent 中也含有 Safari 字樣,Edge 含有 Safari 與 Chrome,Opera 早期含有 MSIE。因此必須把更明確的規則放在前面,否則會大量誤判。

三、直接檢查版本字串

var uat = navigator.userAgent;
if (uat.indexOf("MSIE 6.0") > 0) alert("ie6");
else if (uat.indexOf("MSIE 7.0") > 0) alert("ie7");
else if (uat.indexOf("MSIE 8.0") > 0) alert("ie8");
else if (uat.indexOf("Firefox") > 0) alert("firefox");

最簡單粗暴的一種。IE11 之後 userAgent 中已完全不出現 MSIE,改為 Trident/7.0; rv:11.0,所以這段程式碼對 IE11 完全無效。

四、用 CSS 區分瀏覽器

#example { color: red; }        /* firefox */
* html #example { color: blue; }   /* ie6 */
*+html #example { color: green; }  /* ie7 */

這是利用各瀏覽器 CSS 解析器的 bug 來做 hack。這種做法極度脆弱,任何版本更新都可能讓 hack 失效或影響其他樣式,完全不建議在專案中使用。遇到跨瀏覽器樣式差異,應優先釐清差異來源(box-sizing、預設 margin、flex 對齊行為等)並用標準屬性修正。

五、HTML 條件註釋

<!--[if !IE]><!--> 除 IE 外都可識別 <!--<![endif]-->
<!--[if IE]> 所有的 IE 可識別 <![endif]-->
<!--[if IE 6]> 僅 IE6 可識別 <![endif]-->
<!--[if lt IE 6]> IE6 以及 IE6 以下版本可識別 <![endif]-->
<!--[if gte IE 6]> IE6 以及 IE6 以上版本可識別 <![endif]-->
<!--[if IE 7]> 僅 IE7 可識別 <![endif]-->
<!--[if lt IE 7]> IE7 以及 IE7 以下版本可識別 <![endif]-->
<!--[if gte IE 7]> IE7 以及 IE7 以上版本可識別 <![endif]-->

條件註釋是 IE 獨有的機制,其他瀏覽器會把它當成普通註釋忽略。它比 CSS hack 可靠,但IE10 之後已完全不再支援,因此現在只有維護舊系統時才會用到。

為什麼這些方法都不再推薦

核心問題是:你真正想知道的往往不是「這是什麼瀏覽器」,而是「這個瀏覽器支援什麼功能」。userAgent 字串可以被任意偽造、會隨版本任意變化、且不同瀏覽器之間存在大量共用標記。以它作為分支依據,維護成本極高且容易出錯。

現代的正確做法是特性偵測(feature detection):

// 直接問:這個能力有沒有?
if ('addEventListener' in window) {
  // 走標準路徑
} else {
  // 走相容路徑
}

if (window.Promise) {
  // 支援 Promise
}

if ('IntersectionObserver' in window) {
  // 支援交集觀察器
}

// CSS 也可以用 @supports
@supports (display: grid) {
  .container { display: grid; }
}

若需要與舊瀏覽器相容,用 polyfill 補上缺失的功能,而不是為每個瀏覽器寫一套分支。

真的必須判斷瀏覽器時

有些場景確實繞不開,例如:某些 Safari 版本的日期解析 bug、特定舊版瀏覽器的 video 編碼支援差異。這時建議:

  1. 用成熟的函式庫(如 bowser、platform.js)而非自行維護正則。
  2. 把判斷結果集中在一個工具模組中,並在註解裡寫清楚「為什麼需要這個判斷、影響哪個 bug」。
  3. 盡可能把瀏覽器判斷的範圍縮小,例如 isSafariOnMac() 而不是 isSafari()。
  4. 為判斷加上期限——註明「待 Safari XX 佔比歸零後移除」。

一句話總結:瀏覽器判斷是技術債,能不用就不用;必須用時,請把它寫得明確、集中、可移除。

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