行動版網站常需要針對不同裝置給不同待遇:iOS 上要避開某些字型、Android 上要調整影片播放行為、判斷是否在微信內開啟。做法是讀取 navigator.userAgent,比對其中的關鍵字。
<script type="text/javascript">
var browser = {
versions: function() {
var u = navigator.userAgent, app = navigator.appVersion;
return {
trident: u.indexOf('Trident') > -1, // IE 內核
presto: u.indexOf('Presto') > -1, // Opera 內核
webKit: u.indexOf('AppleWebKit') > -1, // 蘋果、Google 內核
gecko: u.indexOf('Gecko') > -1 && u.indexOf('KHTML') == -1, // 火狐內核
mobile: !!u.match(/AppleWebKit.*Mobile.*/) || !!u.match(/AppleWebKit/),
ios: !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/), // iOS 裝置
android: u.indexOf('Android') > -1 || u.indexOf('Linux') > -1,
iPhone: u.indexOf('iPhone') > -1 || u.indexOf('Mac') > -1,
iPad: u.indexOf('iPad') > -1,
webApp: u.indexOf('Safari') == -1 // 是否為 web app 模式
};
}(),
language: (navigator.browserLanguage || navigator.language).toLowerCase()
};
document.writeln("語言版本: " + browser.language);
document.writeln("是否為移動終端: " + browser.versions.mobile);
document.writeln("iOS 終端: " + browser.versions.ios);
document.writeln("Android 終端: " + browser.versions.android);
document.writeln("是否為 iPhone: " + browser.versions.iPhone);
document.writeln("是否為 iPad: " + browser.versions.iPad);
document.writeln(navigator.userAgent);
</script>
u.indexOf('iPad') 抓不到。需要額外檢查 navigator.maxTouchPoints > 1 才能分辨。webApp 的判斷過於粗糙。它其實是在推測「是否為 Safari」,與是否為全螢幕 PWA 模式沒有直接關係。目前更準確的做法是比對 window.matchMedia('(display-mode: standalone)')。Android 關鍵字即可。console.log。UA 字串可以被任意偽造,且各家瀏覽器版本更迭頻繁,判斷「有沒有這個能力」通常比判斷「是什麼瀏覽器」更可靠:
var supportsTouch = 'ontouchstart' in window;
var supportsGrid = CSS.supports('display', 'grid');
var isStandalone = window.matchMedia('(display-mode: standalone)').matches;
實務上的分工建議是:排版與功能用特徵偵測(搭配 CSS media query 與 @supports),只有確實需要針對特定 App 的瀏覽器行為做補償時,才去讀 userAgent。真要處理複雜的裝置分流,直接採用成熟的 UA 解析庫,也比自己維護一堆 indexOf 來得省心。