網上對瀏覽器類型判斷可能是經過 User agent 字段。可是這種方法是不可靠的,由於 User agent 很容易被修改。javascript
下面介紹的這種判斷的方法符合「鴨子類型」的風格。java
鴨子類型(英語: duck typing)在程序設計中是動態類型的一種風格。在這種風格中,一個對象有效的語義,不是由繼承自特定的類或實現特定的接口,而是由"當前方法和屬性的集合"決定。「鴨子測試」能夠這樣表述:「當看到一隻鳥走起來像鴨子、游泳起來像鴨子、叫起來也像鴨子,那麼這隻鳥就能夠被稱爲鴨子。」web
僅在確實須要時才使用這種瀏覽器檢測方法,例如顯示特定於瀏覽器的安裝擴展說明。儘量使用特徵檢測。chrome
// Opera 8.0+ var isOpera = (!!window.opr && !!opr.addons) || !!window.opera || navigator.userAgent.indexOf(' OPR/') >= 0; // Firefox 1.0+ var isFirefox = typeof InstallTrigger !== 'undefined'; // Safari 3.0+ "[object HTMLElementConstructor]" var isSafari = /constructor/i.test(window.HTMLElement) || (function (p) { return p.toString() === "[object SafariRemoteNotification]"; })(!window['safari'] || (typeof safari !== 'undefined' && safari.pushNotification)); // Internet Explorer 6-11 var isIE = /*@cc_on!@*/false || !!document.documentMode; // Edge 20+ var isEdge = !isIE && !!window.StyleMedia; // Chrome 1 - 79 var isChrome = !!window.chrome && (!!window.chrome.webstore || !!window.chrome.runtime); // Edge (based on chromium) detection var isEdgeChromium = isChrome && (navigator.userAgent.indexOf("Edg") != -1); // Blink engine detection var isBlink = (isChrome || isOpera) && !!window.CSS; var output = 'Detecting browsers by ducktyping:<hr>'; output += 'isFirefox: ' + isFirefox + '<br>'; output += 'isChrome: ' + isChrome + '<br>'; output += 'isSafari: ' + isSafari + '<br>'; output += 'isOpera: ' + isOpera + '<br>'; output += 'isIE: ' + isIE + '<br>'; output += 'isEdge: ' + isEdge + '<br>'; output += 'isEdgeChromium: ' + isEdgeChromium + '<br>'; output += 'isBlink: ' + isBlink + '<br>'; document.body.innerHTML = output;
之前的方法依賴渲染引擎的屬性(-moz-box-sizing
and -webkit-transform
)來判斷瀏覽器類型。這些前綴最終會被棄用。因此我轉而使用更爲健壯的方法——經過具體的瀏覽器的特性。瀏覽器
document.documentMode
。StyleMedia
構造函數Edg/[version]
,如: (ex: "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.16 Safari/537.36 Edg/80.0.361.9")
InstallTrigger
chrome
中,其屬性之中有一個chrome.webstore
對象。可是在最近的版本中,chrome.webstore
將會被棄用。SafariRemoteNotification
,以涵蓋3.0版及更高版本的 Safari。window.opera
已經存在了不少年,可是將隨着 Opera 將內核替換爲 Blink + V8 而被棄用。Opera 15 中,user agent 字段更像 Chrome 的,可是額外的加入了 「OPR」。在這個本版中,chrome
對象一樣被定義,可是沒有 chrome.webstore
。自從 Opera 開始極力克隆 Chrome 後,我便使用 user agent 來判斷它。ide
!!window.opr && opr.addons
仍然能夠用來識別 Opera 20 以上的版本!函數
CSS.supports()
被引入 Blink。理所固然的,一樣的 Blink 也會被 Opera 使用。