若要針對不同瀏覽器微調顯示或功能,常見做法是讀取 navigator.userAgent,再從中判斷關鍵字。
var ua = navigator.userAgent;
if (ua.indexOf('Firefox') > -1) {
// Firefox
} else if (ua.indexOf('Chrome') > -1) {
// Chrome
} else if (ua.indexOf('MSIE') > -1) {
// 舊版 IE
}
例如 360 瀏覽器的相容模式可能使用 IE 核心,極速模式則可能使用 Chromium 核心,因此 userAgent 內容會不同。
userAgent 只能作為輔助判斷,不建議作為主要功能依據。更穩定的方式,是檢測瀏覽器是否支援某個 API。