navigator.userAgent可获取浏览器信息字符串,但易被篡改,仅适用于软判断;应优先使用特性检测,必要时结合navigator.vendor等字段交叉验证。

用 navigator.userAgent 拿原始字符串最直接
现代浏览器基本都支持 navigator.userAgent,它返回一串包含浏览器名、版本、内核、操作系统等信息的字符串。比如 Chrome 125 在 Windows 上可能返回:Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.0.0 Safari/537.36
注意:这个值可被 JS 修改(navigator.__defineGetter__ 或 DevTools 注入),也常被用户代理切换插件覆盖,所以只适合做「软判断」或降级提示,不能用于权限控制或安全逻辑。
常见误操作:
• 直接用 includes('Chrome') 判断——Safari 和 Edge 的 UA 里也可能含 Chrome(因 Chromium 内核)
• 依赖 userAgent 区分移动端——iOS 的 Safari 和 Chrome UA 都带 iPhone 或 iPad,但安卓 Chrome 可能不带 Android(某些定制 ROM)
用 navigator.vendor 和 navigator.product 辅助交叉验证
这两个字段比 userAgent 更稳定,且不易被伪造:
• navigator.vendor 通常返回 Google Inc.(Chrome)、Apple Computer, Inc.(Safari)、Microsoft Corporation(Edge)
• navigator.product 多数情况是 Gecko(Firefox)或 WebKit(Safari / Chrome / Edge)
实操建议:
• 先看 navigator.vendor:若为 Apple Computer, Inc.,基本可锁定 Safari
• 再结合 navigator.userAgent 中是否含 Edg/ 或 Firefox/ 做排除
• 不要单独依赖 navigator.product === 'Gecko'——旧版 Chrome 曾短暂返回过 Gecko,已淘汰但仍有极少数遗留环境
检测 Firefox 要避开 rv: 版本陷阱
Firefox 的 UA 格式是 Mozilla/5.0 (...) Gecko/20100101 Firefox/126.0,但关键版本号实际在 rv:126.0 里(括号内)。早期 Firefox 会把真实版本写在 rv: 后,而 Firefox/ 后面可能是伪装值。
正确提取方式:
• 优先匹配 rv:(\d+\.\d+)(正则捕获)
• 回退匹配 Firefox/(\d+\.\d+)(仅当无 rv: 时)
• 避免用 indexOf('Firefox') 就认为是 Firefox——某些国产双核浏览器(如 360 极速)UA 里也硬塞了 Firefox/ 字段
真正需要区分浏览器时,优先 feature detection 而非 UA sniffing
绝大多数场景其实不需要知道「是不是 Chrome」,而是想知道「能不能用 ResizeObserver」或「scrollTo 是否支持 behavior: 'smooth'」。这类问题用特性检测更可靠:
立即学习“前端免费学习笔记(深入)”;
例如判断是否支持 scrollIntoView 平滑滚动:
if ('scrollBehavior' in document.documentElement.style) {<br> element.scrollIntoView({ behavior: 'smooth' });<br>} else {<br> element.scrollIntoView();<br>}
再比如检测 WebP 支持:
const webp = new Image();<br>webp.onload = webp.onerror = () => {<br> if (webp.height === 1) console.log('WebP supported');<br>};<br>webp.src = 'data:image/webp;base64,UklGRiQAAABXRUJQVlA4IBgAAAAwAgSSgACZAGoAAAAB';
UA 判断容易过时——新浏览器一发布,正则就得改;而特性检测只要 API 存在就一直有效。只有当必须给特定浏览器打补丁(比如 Safari 15.4 的 input[type=date] 渲染 bug),才值得动用 UA。


















