通過navigator.userAgent或navigator.platform判斷設備類型並跳轉,是早期移動適配常用手段。本文分析UA檢測的局限性,提供改進版檢測代碼,並推薦現代響應式設計、服務端渲染分發、PWA等更優替代方案。
<script>
var system = { win: false, mac: false, xll: false };
var p = navigator.platform;
system.win = p.indexOf("Win") === 0;
system.mac = p.indexOf("Mac") === 0;
system.x11 = (p === "X11") || (p.indexOf("Linux") === 0);
if (system.win || system.mac || system.xll) { // ❌ xll 永遠為 false
window.location.href = "login.jsp"; // PC端
} else {
window.location.href = "wapLogin.jsp"; // 移動端
}
</script>
system.xll 拼寫錯誤,應為system.x11navigator.platform僅反映作業系統,無法區分手機/平板/桌面 (iPadOS 13+ 報告 "MacIntel")function isMobile() {
var ua = navigator.userAgent.toLowerCase();
var mobileKeywords = [
'android', 'iphone', 'ipod', 'ipad', 'windows phone',
'blackberry', 'webos', 'opera mini', 'opera mobi', 'iemobile'
];
return mobileKeywords.some(k => ua.includes(k));
}
// 使用
if (isMobile()) {
location.href = 'wapLogin.jsp';
} else {
location.href = 'login.jsp';
}
<!-- HTML -->
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- CSS -->
@media (max-width: 768px) {
.pc-only { display: none; }
.mobile-menu { display: block; }
}
@media (min-width: 769px) {
.mobile-only { display: none; }
.pc-sidebar { display: block; }
}
// Next.js getServerSideProps 示例
export async function getServerSideProps({ req }) {
const ua = req.headers['user-agent'] || '';
const isMobile = /mobile|android|iphone/i.test(ua);
return { props: { isMobile } };
}
// 頁面組件
export default function Login({ isMobile }) {
return isMobile ? <MobileLogin /> : <DesktopLogin />;
}
<!-- 僅在極少數舊系統強制分離時使用 -->
<script>
(function() {
var mobile = /android|iphone|ipad|ipod|mobile/i.test(navigator.userAgent);
var target = mobile ? '/m/' : '/';
if (location.pathname.indexOf(target) !== 0) {
location.replace(target); // replace 避免歷史棧污染
}
})();
</script>
location.replace、保留查詢參數、設定sessionStorage防閃爍)navigator.platform、獨立m站、雙套維護