// 易被偽造、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);
}
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;
}
npm i ua-parser-jsimport 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)
// 僅在 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) {
// 啟用新功能
}
navigator.userAgent.indexOf("Chrome") 作為核心邏輯判斷依據。