萬盛學電腦網

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

JavaScript 偵測裝置類型 (PC/行動裝置) 完整指南:User-Agent、特徵偵測、Flash 替代策略

核心需求

許多行動裝置不支援 Flash,需在載入頁面時判斷裝置類型,決定載入 .swf (PC) 或 .gif (行動裝置) 等替代內容。

方案一:User-Agent 字串判斷 (傳統、簡單、易偽造)

function isMobileUA() {
    var ua = navigator.userAgent.toLowerCase();
    var mobileKeywords = [
        'mobile', 'android', 'iphone', 'ipad', 'ipod', 
        'blackberry', 'windows phone', 'opera mini', 'iemobile'
    ];
    return mobileKeywords.some(function(kw) { return ua.indexOf(kw) > -1; });
}

// 使用
if (isMobileUA()) {
    // 載入 GIF/HTML5 動畫
} else {
    // 載入 Flash SWF
}

方案二:特徵偵測 - 觸控支援 (現代、較可靠)

function isTouchDevice() {
    return ('ontouchstart' in window) || 
           (navigator.maxTouchPoints > 0) || 
           (navigator.msMaxTouchPoints > 0); // IE10/11
}

// 更精確:判斷「主要輸入裝置為觸控」
function isPrimaryTouch() {
    return window.matchMedia('(pointer:coarse)').matches;
}

方案三:綜合判斷函數 (Flash 檢測 + 裝置類型)

/**
 * 綜合檢測:Flash 支援度 + 裝置類型
 * @returns {Object} { hasFlash: Boolean, flashVersion: Number, isMobile: Boolean }
 */
function detectFlashAndDevice() {
    var hasFlash = false;
    var flashVersion = 0;
    var isMobile = isMobileUA() || isTouchDevice(); // 綜合判斷
    
    // Flash 檢測 (僅桌面瀏覽器相關)
    if (!isMobile) {
        if (/*@cc_on!@*/false) { // IE 條件編譯
            try {
                var swf = new ActiveXObject('ShockwaveFlash.ShockwaveFlash');
                if (swf) {
                    hasFlash = true;
                    var verStr = swf.GetVariable('$version'); // "WIN 32,0,0,100"
                    flashVersion = parseInt(verStr.split(' ')[1].split(',')[0], 10);
                }
            } catch (e) {}
        } else if (navigator.plugins && navigator.plugins['Shockwave Flash']) {
            var plugin = navigator.plugins['Shockwave Flash'];
            hasFlash = true;
            var desc = plugin.description; // "Shockwave Flash 32.0 r0"
            flashVersion = parseInt(desc.match(/\d+/)[0], 10);
        }
    }
    
    return { hasFlash: hasFlash, flashVersion: flashVersion, isMobile: isMobile };
}

// 使用範例
var detect = detectFlashAndDevice();
if (detect.isMobile || !detect.hasFlash) {
    // 載入替代內容 (GIF/HTML5/靜態圖)
    renderFallback();
} else {
    // 載入 Flash
    renderFlash(detect.flashVersion);
}

方案四:現代最佳實踐 - 完全移除 Flash,改用 HTML5

Adobe Flash 已於 2020/12/31 終止支援**,所有主流瀏覽器已移除 Flash Player。新專案**嚴禁使用 Flash**,現有專案應全面遷移:

響應式圖片/動畫載入策略 (無 Flash 時代)

<picture>
    <!-- 行動裝置優先:輕量 GIF/WebP -->
    <source media="(max-width: 767px)" srcset="animation-mobile.webp" type="image/webp">
    <source media="(max-width: 767px)" srcset="animation-mobile.gif">
    
    <!-- 桌面:高品質 MP4/Lottie -->
    <source media="(min-width: 768px)" srcset="animation-desktop.mp4" type="video/mp4">
    
    <!-- 回退 -->
    <img src="fallback.jpg" alt="動畫內容">
</picture>

<!-- 或 Lottie JSON 動畫 (向量、體積小、可互動) -->
<div id="lottie-container"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bodymovin/5.9.0/lottie.min.js"></script>
<script>
    lottie.loadAnimation({
        container: document.getElementById('lottie-container'),
        renderer: 'svg',
        loop: true,
        autoplay: true,
        path: 'animation.json' // 導出自 After Effects + Bodymovin
    });
</script>

裝置判斷現代工具庫

  • ua-parser-js:詳細解析 UA 字串 (瀏覽器、OS、裝置、引擎)
  • bowser:輕量級瀏覽器偵測
  • mobile-detect:專注行動裝置偵測
  • is-mobile:單一功能、Tree-shakable

總結

  1. Flash 已死,**不要再寫 Flash 偵測/替代邏輯**,直接用 HTML5 技術棧。
  2. 若確需區分裝置體驗 (如觸控優化、響應式圖片),用 matchMedia('(pointer:coarse)') 或 navigator.maxTouchPoints。
  3. User-Agent 判斷僅作為輔助參考,**不可作為核心邏輯依據** (易偽造、維護成本高)。
  4. 響應式設計 (RWD) + 漸進增強 才是跨裝置的正確道路。
copyright © 萬盛學電腦網 all rights reserved
原 Flash 用途現代替代技術
影片播放<video> + H.264/VP9/WebM、HLS/DASH 串流
動畫/互動Canvas API、WebGL、SVG SMIL、CSS Animation、Lottie (Bodymovin)
遊戲WebGL (Three.js, Babylon.js)、WebAssembly
豐富文字編輯contenteditable + ExecCommand / Input Events API / Slate/ProseMirror
檔案上傳/攝影機<input type="file" accept="image/*" capture>, MediaDevices API