Try   HackMD

What's the difference between feature detection, feature inference, and using the UA string?

前言

該題目主要探討「針對某特定代碼(某功能),能否在某瀏覽器版本正常運作,避免用戶糟糕的體驗」

feature detection 功能檢測 (the best)

針對特定瀏覽器檢查是否支援某段代碼、某個功能是否存在

(一) 直接在該瀏覽器開發者工具運行、或者開檔測試

if (window.XMLHttpRequest) {
    new XMLHttpRequest();
}

----
if (window.XMLHttpRequests) {
    new XMLHttpRequest();
}

(二) 使用library

Modernizr

(該函式庫在2017就沒有更新過消息,但github還是有在更新,所以使用前可能需要確認該功能在Modernizr是不是最新的)

feature inference 功能推斷

根據某功能存在,進而推斷另一個功能也存在

if('localStorage' in window){
   window.sessionStorage.setItem("this-should-exist", 1);
   
   // type error
if('localStorages' in window){
   window.sessionStorage.setItem("this-should-exist-too", 1);
}

UA string (不推薦)

User Agent 所有瀏覽器都有一個用戶代理字符串,用於標識瀏覽器是什麼(版本、名稱、操作系統等)。
過去IE、Netscape 的時代,開發者曾經用browser sniffing code的方式檢測 -> 先查出user的瀏覽器再給予適當的處理。

  • 以現在環境來說,US String對檢測是沒什麼可參考性的方式。因為現今瀏覽器眾多且版本不斷迭代,不可能一一每個更改、對每個做檢測。
  • 某些瀏覽器甚至謊稱自己的字符串,並提供用戶自行修改的功能,所以一切都變得毫無意義。
  • 在dev tool用navigator.userAgent查找自己的string

筆者browser舉例

  • Chrome
    Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.114 Safari/537.36
  • Safari
    Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.1.3 Safari/605.1.15
  • Firefox
    Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:89.0) Gecko/20100101 Firefox/89.0

可以看到在Chrome裡甚至會放safari的版本,但他根本不是safari

  • MDN:永遠不要使用browser sniffing code

總結

  1. 查找起來並不是一個common的考題,稍微懂三個區別以及最好的方式是「功能檢測」
  2. 可以先嘗試之前行業比較推崇的 Modernizr 庫
  3. 別用UA String
參考文章

原題目出處 - stackoverflow
MDN - https://developer.mozilla.org/zh-CN/docs/Learn/Tools_and_testing/Cross_browser_testing/Feature_detection

Feature Inference