萬盛學電腦網

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

JavaScript 偵測 Chrome 瀏覽器的正規寫法與 User-Agent 解析

❌ 不推薦:User-Agent 字串檢測

// 易被偽造、Chrome 版本號變動大、Edge/Opera/Brave 也含 "Chrome"
const isChromeUA = navigator.userAgent.includes("Chrome");

✅ 推薦:特徵偵測

針對 **Chrome 專有 API** 檢測,而非 UA 字串:

// 1. chrome 物件(擴充套件/開發者工具環境常存在)
const isChrome = !!window.chrome && !!window.chrome.webstore;

// 2. CSS Paint API (Chrome 65+)
const isChromePaint = "PaintWorklet" in window;

// 3. WebGPU (Chrome 113+)
const isChromeWebGPU = "gpu" in navigator;

// 綜合判斷
function isChromeBrowser() {
    return !!window.chrome && (!!window.chrome.webstore || "PaintWorklet" in window);
}

User-Agent Client Hints(現代標準,Chrome 89+)

async function getBrowserInfo() {
    if (!navigator.userAgentData) return null; // 不支援 Client Hints
    const {brands} = await navigator.userAgentData.getHighEntropyValues(["brands"]);
    // brands 範例:[{brand: "Google Chrome", version: "119"}, {brand: "Chromium", version: "119"}, ...]
    const chromeBrand = brands.find(b => b.brand === "Google Chrome" || b.brand === "Chromium");
    return chromeBrand ? {name: chromeBrand.brand, version: chromeBrand.version} : null;
}

UA 解析庫(若必須解析 UA 字串)

  • ua-parser-js:輕量、準確、支援 Node/瀏覽器 npm i ua-parser-js
  • bowser:專注瀏覽器判斷
import UAParser from "ua-parser-js";
const parser = new UAParser();
const result = parser.getResult();
console.log(result.browser.name); // "Chrome"
console.log(result.browser.version); // "119.0.0.0"
console.log(result.os.name); // "Windows"
console.log(result.device.type); // undefined (desktop)

條件載入 Polyfill/修正 Chrome Bug 範例

// 僅在 Chrome 載入特定修正
if (isChromeBrowser()) {
    import("./chrome-fix.js").then(mod => mod.applyFix());
}

// 或根據版本號
if (isChromeBrowser() && parseInt(navigator.userAgentData?.brands?.find(b=>b.brand==="Chromium")?.version || "0") >= 110) {
    // 啟用新功能
}

總結

  1. **優先用特徵偵測**(Feature Detection),而非 UA 字串。
  2. 需精確版本/品牌資訊時,用 **User-Agent Client Hints** API。
  3. 複雜解析場景引入 **ua-parser-js**。
  4. **切勿**用 navigator.userAgent.indexOf("Chrome") 作為核心邏輯判斷依據。
copyright © 萬盛學電腦網 all rights reserved