如何区分不同浏览器的User Agent?求更可靠检测方法
如何区分MacOS上的Safari与Chrome浏览器?
一、通过User Agent字符串精准识别
对比你给出的两款浏览器UA:
- Safari的UA包含
Version/[版本号]和Safari/[WebKit内核版本],且无Chrome/字段:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.1 Safari/605.1.15 - Chrome的UA包含
Chrome/[版本号],且Safari/后的版本对应Blink内核(通常是537.36系列),无Version/字段:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36
可以用正则表达式快速匹配:
// 检测是否为Safari function isSafari() { const ua = navigator.userAgent; return /Version\/[\d.]+ Safari\/[\d.]+/.test(ua) && !/Chrome\/[\d.]+/.test(ua); } // 检测是否为Chrome function isChrome() { const ua = navigator.userAgent; return /Chrome\/[\d.]+/.test(ua) && /Safari\/537.36/.test(ua); }
二、通过浏览器专属对象/API检测
这是你提到的方法的升级版,结合更多专属特征提升可靠性:
- Safari专属:
window.safari对象仅在Safari中存在,同时navigator.vendor返回Apple Computer, Inc. - Chrome专属:
window.chrome对象在Chrome中稳定存在,navigator.vendor返回Google Inc.
示例代码:
function isSafari() { return typeof window.safari !== 'undefined' && navigator.vendor === 'Apple Computer, Inc.'; } function isChrome() { return typeof window.chrome !== 'undefined' && navigator.vendor === 'Google Inc.'; }
注:部分Chrome衍生浏览器(如Edge)也会有
window.chrome,但Mac上主流的只有Chrome本身,结合navigator.vendor可进一步区分。
三、通过内核特性差异检测
Safari基于原生WebKit,Chrome基于Blink(WebKit分支),两者部分API支持有差异:
- Safari支持
webkitConvertPointFromNodeToPage这类WebKit专属方法,Chrome不支持 - Chrome支持
chrome.runtime等扩展相关API(即使无扩展也存在该对象)
示例代码:
// 基于WebKit专属API检测Safari function isSafari() { return typeof document.webkitConvertPointFromNodeToPage === 'function'; } // 基于Chrome扩展API检测Chrome function isChrome() { return typeof chrome.runtime !== 'undefined'; }
综合建议
优先组合User Agent匹配+专属对象检测,既能避免单一方法的误判,又能覆盖绝大多数场景:
function detectBrowser() { const ua = navigator.userAgent; const vendor = navigator.vendor; if (/Chrome\/[\d.]+/.test(ua) && vendor === 'Google Inc.' && typeof window.chrome !== 'undefined') { return 'Chrome'; } else if (/Version\/[\d.]+ Safari\/[\d.]+/.test(ua) && vendor === 'Apple Computer, Inc.' && typeof window.safari !== 'undefined') { return 'Safari'; } return 'Unknown'; }
内容的提问来源于stack exchange,提问作者Nex
相关产品推荐
相关产品推荐

