To detect the user’s browser (Chrome, Safari, Firefox, Edge) in JavaScript, prefer feature detection (checking for specific APIs/behaviors) whenever possible, and when browser identity is actually needed, combine User-Agent Client Hints (navigator.userAgentData) with a careful navigator.userAgent fallback—checking Edge (Edg/) and Chrome (Chrome/ / CriOS/) before Safari (Safari/) because Chromium and Edge user-agent strings also contain "Safari". Treat browser detection as a best-effort heuristic rather than a security boundary, since headers and navigator properties can be spoofed, masked, or reduced in modern browsers.
1. Detecting Edge, Chrome, Firefox, and Safari Safely
Order your checks carefully—Edge (Edg/) and Chrome (Chrome/ or CriOS/ on iOS) include "Safari" in their UA strings, while Firefox (Firefox/ or FxiOS/ on iOS) does not, and true desktop/iOS Safari has "Safari" without "Chrome", "Chromium", "Edg", or "OPR":
// Detect major browsers using User-Agent Client Hints first, then UA fallback
function detectBrowser(nav = typeof navigator !== "undefined" ? navigator : null) {
if (!nav) {
return { name: "unknown", version: null };
}
const uaData = nav.userAgentData;
if (uaData && Array.isArray(uaData.brands)) {
const brandList = uaData.brands.map((b) => ({
brand: String(b.brand || ""),
version: String(b.version || "")
}));
const edgeBrand = brandList.find((b) => /edge/i.test(b.brand));
if (edgeBrand) {
return { name: "Edge", version: edgeBrand.version || null };
}
const chromeBrand = brandList.find((b) => /google chrome/i.test(b.brand));
if (chromeBrand) {
return { name: "Chrome", version: chromeBrand.version || null };
}
}
const ua = typeof nav.userAgent === "string" ? nav.userAgent : "";
if (!ua) {
return { name: "unknown", version: null };
}
// 1. Microsoft Edge (Chromium)
const edgeMatch = ua.match(/Edg(?:e|A|iOS)?\/([\d.]+)/);
if (edgeMatch) {
return { name: "Edge", version: edgeMatch[1] };
}
// 2. Firefox (desktop and iOS)
const firefoxMatch = ua.match(/(?:Firefox|FxiOS)\/([\d.]+)/);
if (firefoxMatch) {
return { name: "Firefox", version: firefoxMatch[1] };
}
// 3. Chrome (desktop and iOS CriOS), excluding Edge/Opera/Chromium wrappers
const chromeMatch = ua.match(/(?:Chrome|CriOS)\/([\d.]+)/);
if (chromeMatch && !/OPR\//.test(ua)) {
return { name: "Chrome", version: chromeMatch[1] };
}
// 4. Safari (must come after Chrome/Edge checks)
const safariMatch = ua.match(/Version\/([\d.]+).*Safari\//);
if (safariMatch && !/(?:Chrome|CriOS|Chromium|Edg|OPR|Firefox|FxiOS)/.test(ua)) {
return { name: "Safari", version: safariMatch[1] };
}
return { name: "unknown", version: null };
}
// Example usage:
console.log(detectBrowser());
// { name: "Chrome", version: "..." } (varies by client)
- Check
Edg/andChrome/beforeSafari/: Chromium-based browsers appendSafari/537.36for compatibility, which trips up naive"Safari"substring checks. - Account for iOS wrappers: On iOS/iPadOS, third-party browsers use WebKit under the hood and report tokens like
CriOS(Chrome) orFxiOS(Firefox).
2. Prefer Feature Detection Over Browser Sniffing
Before branching logic on browser name or version, test whether the actual web API or CSS capability exists—feature detection works across new releases and alternative browsers without brittle version tables:
// Feature detection example: check Clipboard API & CSS container support
function getClientCapabilities() {
const hasClipboardWrite =
typeof navigator !== "undefined" &&
Boolean(navigator.clipboard && typeof navigator.clipboard.writeText === "function");
const hasContainerQueries =
typeof CSS !== "undefined" &&
typeof CSS.supports === "function" &&
CSS.supports("container-type: inline-size");
const hasResizeObserver = typeof ResizeObserver === "function";
return {
hasClipboardWrite,
hasContainerQueries,
hasResizeObserver
};
}
// Example usage:
console.log(getClientCapabilities());
- Resilient to browser updates: A feature check stays valid even when a browser ships a feature in a minor release or a new browser enters the market.
- Reserve UA detection for genuine quirks: Use browser/version detection only when a known rendering or API bug lacks a clean feature test.
3. UA Reduction, Client Hints, and Spoofing Gotchas
Modern browsers apply User-Agent Reduction (freezing legacy minor/patch numbers and platform strings in navigator.userAgent) while exposing structured brand/version info via navigator.userAgentData (available in Chromium-based browsers, with getHighEntropyValues() needed for full version numbers):
// Query high-entropy UA client hint version details when supported
async function getDetailedBrowserInfo() {
const basic = detectBrowser();
const uaData = typeof navigator !== "undefined" ? navigator.userAgentData : null;
if (!uaData || typeof uaData.getHighEntropyValues !== "function") {
return basic;
}
try {
const highEntropy = await uaData.getHighEntropyValues(["fullVersionList", "platform"]);
return {
...basic,
platform: highEntropy.platform ?? basic.name,
fullVersionList: highEntropy.fullVersionList ?? []
};
} catch {
return basic;
}
}
// Example usage:
// getDetailedBrowserInfo().then(console.log);
- Never trust UA/Client Hints for security or access control: Users, extensions, headless browsers, and proxies can alter
userAgentor headers at will. - Expect
"unknown"on custom/embedded webviews: In-app webviews, privacy tools, or non-standard clients may omit expected tokens.
