萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

JavaScript移動端/PC端自動跳轉:User-Agent檢測與現代響應式替代方案

通過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.x11
  • navigator.platform僅反映作業系統,無法區分手機/平板/桌面 (iPadOS 13+ 報告 "MacIntel")
  • UA字符串極易偽造、變化快、維護成本高
  • 跳轉導致SEO受損、分享鏈接失效、雙維護成本

改進版 UA 檢測 (僅作為備選)

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; }
}

服務端渲染分發 (SSR/Next.js/Nuxt.js)

// 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 />;
}

漸進式Web應用 (PWA) 統一入口

  • 單一URL,Service Worker離線緩存
  • Web App Manifest 提供安裝到主屏體驗
  • 響應式布局自適應所有屏幕

不得不跳轉時的最小化方案

<!-- 僅在極少數舊系統強制分離時使用 -->
<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>

總結建議

  1. 首選:響應式設計 + 單一代碼庫
  2. 次選:服務端UA分發渲染不同模板
  3. 最後手段:客戶端JS跳轉 (使用location.replace、保留查詢參數、設定sessionStorage防閃爍)
  4. 棄用:navigator.platform、獨立m站、雙套維護
copyright © 萬盛學電腦網 all rights reserved