Search K
Appearance
Appearance
📊 SEO元描述:2024年最新navigator对象教程,详解浏览器信息检测、用户代理字符串解析、设备特性检测。包含完整代码示例,适合JavaScript开发者掌握浏览器兼容性处理。
核心关键词:navigator对象、浏览器检测、用户代理字符串、设备特性检测、浏览器兼容性
长尾关键词:navigator对象怎么用、JavaScript浏览器检测、用户代理解析、设备类型判断、浏览器特性检测
通过本节navigator对象详解,你将系统性掌握:
navigator对象是什么?这是Web开发中处理兼容性问题的关键工具。navigator对象是浏览器提供的信息检测接口,也是实现跨浏览器兼容性的重要基础。
💡 学习建议:现代Web开发更推荐特性检测而非浏览器检测,但了解navigator对象仍然很重要
navigator对象 提供了丰富的浏览器和系统信息:
// 🎉 navigator对象基本属性示例
class BrowserDetector {
constructor() {
this.navigator = window.navigator;
}
// 获取基本浏览器信息
getBasicInfo() {
return {
// 用户代理字符串
userAgent: this.navigator.userAgent,
// 应用程序名称
appName: this.navigator.appName,
// 应用程序版本
appVersion: this.navigator.appVersion,
// 应用程序代码名称
appCodeName: this.navigator.appCodeName,
// 平台信息
platform: this.navigator.platform,
// 产品名称
product: this.navigator.product,
// 产品子版本
productSub: this.navigator.productSub,
// 供应商信息
vendor: this.navigator.vendor,
// 供应商子版本
vendorSub: this.navigator.vendorSub,
// 浏览器语言
language: this.navigator.language,
// 支持的语言列表
languages: this.navigator.languages,
// 是否启用Cookie
cookieEnabled: this.navigator.cookieEnabled,
// 是否在线
onLine: this.navigator.onLine,
// 硬件并发数(CPU核心数)
hardwareConcurrency: this.navigator.hardwareConcurrency,
// 设备内存(GB)
deviceMemory: this.navigator.deviceMemory,
// 最大触摸点数
maxTouchPoints: this.navigator.maxTouchPoints
};
}
// 格式化显示浏览器信息
displayInfo() {
const info = this.getBasicInfo();
console.group('浏览器基本信息');
Object.entries(info).forEach(([key, value]) => {
console.log(`${key}:`, value);
});
console.groupEnd();
return info;
}
// 检测浏览器类型
detectBrowser() {
const ua = this.navigator.userAgent.toLowerCase();
const browsers = [
{ name: 'Chrome', test: /chrome\/(\d+)/ },
{ name: 'Firefox', test: /firefox\/(\d+)/ },
{ name: 'Safari', test: /safari\/(\d+)/ },
{ name: 'Edge', test: /edg\/(\d+)/ },
{ name: 'Opera', test: /opera\/(\d+)|opr\/(\d+)/ },
{ name: 'Internet Explorer', test: /msie (\d+)|trident.*rv:(\d+)/ }
];
for (const browser of browsers) {
const match = ua.match(browser.test);
if (match) {
return {
name: browser.name,
version: match[1] || match[2] || 'unknown',
fullMatch: match[0]
};
}
}
return { name: 'Unknown', version: 'unknown' };
}
// 检测操作系统
detectOS() {
const ua = this.navigator.userAgent;
const platform = this.navigator.platform;
const systems = [
{ name: 'Windows', test: /Windows NT (\d+\.\d+)/ },
{ name: 'macOS', test: /Mac OS X (\d+[._]\d+[._]\d+)/ },
{ name: 'Linux', test: /Linux/ },
{ name: 'Android', test: /Android (\d+\.\d+)/ },
{ name: 'iOS', test: /OS (\d+_\d+)/ },
{ name: 'Chrome OS', test: /CrOS/ }
];
for (const system of systems) {
const match = ua.match(system.test);
if (match) {
return {
name: system.name,
version: match[1] ? match[1].replace(/_/g, '.') : 'unknown',
platform: platform
};
}
}
return { name: 'Unknown', version: 'unknown', platform: platform };
}
// 检测设备类型
detectDevice() {
const ua = this.navigator.userAgent;
const maxTouchPoints = this.navigator.maxTouchPoints || 0;
// 移动设备检测
const mobileRegex = /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i;
const tabletRegex = /iPad|Android(?=.*\bMobile\b)/i;
if (tabletRegex.test(ua)) {
return {
type: 'tablet',
isMobile: true,
isTouch: maxTouchPoints > 0,
maxTouchPoints: maxTouchPoints
};
} else if (mobileRegex.test(ua)) {
return {
type: 'mobile',
isMobile: true,
isTouch: maxTouchPoints > 0,
maxTouchPoints: maxTouchPoints
};
} else {
return {
type: 'desktop',
isMobile: false,
isTouch: maxTouchPoints > 0,
maxTouchPoints: maxTouchPoints
};
}
}
}
// 使用浏览器检测器
const detector = new BrowserDetector();
// 显示基本信息
detector.displayInfo();
// 检测浏览器
const browserInfo = detector.detectBrowser();
console.log('浏览器信息:', browserInfo);
// 检测操作系统
const osInfo = detector.detectOS();
console.log('操作系统信息:', osInfo);
// 检测设备类型
const deviceInfo = detector.detectDevice();
console.log('设备信息:', deviceInfo);// 🎉 用户代理字符串解析示例
class UserAgentParser {
constructor(userAgent = navigator.userAgent) {
this.userAgent = userAgent;
this.parsed = this.parse();
}
// 解析用户代理字符串
parse() {
const ua = this.userAgent;
return {
browser: this.parseBrowser(ua),
engine: this.parseEngine(ua),
os: this.parseOS(ua),
device: this.parseDevice(ua),
features: this.parseFeatures(ua)
};
}
// 解析浏览器信息
parseBrowser(ua) {
const browsers = [
{
name: 'Chrome',
regex: /Chrome\/(\d+)\.(\d+)\.(\d+)\.(\d+)/,
versionIndex: [1, 2, 3, 4]
},
{
name: 'Firefox',
regex: /Firefox\/(\d+)\.(\d+)/,
versionIndex: [1, 2]
},
{
name: 'Safari',
regex: /Version\/(\d+)\.(\d+)(?:\.(\d+))?\s+Safari/,
versionIndex: [1, 2, 3]
},
{
name: 'Edge',
regex: /Edg\/(\d+)\.(\d+)\.(\d+)\.(\d+)/,
versionIndex: [1, 2, 3, 4]
},
{
name: 'Opera',
regex: /OPR\/(\d+)\.(\d+)\.(\d+)\.(\d+)/,
versionIndex: [1, 2, 3, 4]
}
];
for (const browser of browsers) {
const match = ua.match(browser.regex);
if (match) {
const version = browser.versionIndex
.map(index => match[index])
.filter(v => v)
.join('.');
return {
name: browser.name,
version: version,
major: parseInt(match[browser.versionIndex[0]]),
full: match[0]
};
}
}
return { name: 'Unknown', version: 'unknown' };
}
// 解析渲染引擎
parseEngine(ua) {
const engines = [
{ name: 'Blink', regex: /Chrome\/\d+/ },
{ name: 'Gecko', regex: /Gecko\/\d+/ },
{ name: 'WebKit', regex: /WebKit\/(\d+)/ },
{ name: 'Trident', regex: /Trident\/(\d+)/ },
{ name: 'EdgeHTML', regex: /Edge\/(\d+)/ }
];
for (const engine of engines) {
const match = ua.match(engine.regex);
if (match) {
return {
name: engine.name,
version: match[1] || 'unknown'
};
}
}
return { name: 'Unknown', version: 'unknown' };
}
// 解析操作系统详细信息
parseOS(ua) {
const systems = [
{
name: 'Windows',
regex: /Windows NT (\d+)\.(\d+)/,
versions: {
'10.0': 'Windows 10',
'6.3': 'Windows 8.1',
'6.2': 'Windows 8',
'6.1': 'Windows 7',
'6.0': 'Windows Vista'
}
},
{
name: 'macOS',
regex: /Mac OS X (\d+)[._](\d+)[._](\d+)/,
formatter: (match) => `macOS ${match[1]}.${match[2]}.${match[3]}`
},
{
name: 'iOS',
regex: /OS (\d+)_(\d+)(?:_(\d+))?/,
formatter: (match) => `iOS ${match[1]}.${match[2]}${match[3] ? '.' + match[3] : ''}`
},
{
name: 'Android',
regex: /Android (\d+)\.(\d+)(?:\.(\d+))?/,
formatter: (match) => `Android ${match[1]}.${match[2]}${match[3] ? '.' + match[3] : ''}`
}
];
for (const system of systems) {
const match = ua.match(system.regex);
if (match) {
let version = match[1] + '.' + match[2];
let fullName = system.name;
if (system.versions && system.versions[version]) {
fullName = system.versions[version];
} else if (system.formatter) {
fullName = system.formatter(match);
}
return {
name: system.name,
version: version,
fullName: fullName,
architecture: this.parseArchitecture(ua)
};
}
}
return { name: 'Unknown', version: 'unknown' };
}
// 解析架构信息
parseArchitecture(ua) {
if (/WOW64|Win64|x64/.test(ua)) return 'x64';
if (/ARM/.test(ua)) return 'ARM';
if (/x86/.test(ua)) return 'x86';
return 'unknown';
}
// 解析设备特征
parseDevice(ua) {
const device = {
type: 'desktop',
vendor: 'unknown',
model: 'unknown'
};
// 移动设备检测
if (/iPhone/.test(ua)) {
device.type = 'mobile';
device.vendor = 'Apple';
const match = ua.match(/iPhone OS (\d+)_(\d+)/);
if (match) {
device.model = `iPhone (iOS ${match[1]}.${match[2]})`;
}
} else if (/iPad/.test(ua)) {
device.type = 'tablet';
device.vendor = 'Apple';
device.model = 'iPad';
} else if (/Android/.test(ua)) {
device.type = /Mobile/.test(ua) ? 'mobile' : 'tablet';
device.vendor = 'Android';
// 尝试提取设备型号
const modelMatch = ua.match(/;\s*([^)]+)\s*\)/);
if (modelMatch) {
device.model = modelMatch[1];
}
}
return device;
}
// 解析特殊特征
parseFeatures(ua) {
return {
isWebView: /wv/.test(ua),
isBot: /bot|crawler|spider/i.test(ua),
isHeadless: /HeadlessChrome/.test(ua),
supportsPWA: 'serviceWorker' in navigator,
supportsWebGL: !!window.WebGLRenderingContext,
supportsWebRTC: !!(navigator.mediaDevices && navigator.mediaDevices.getUserMedia)
};
}
// 获取解析结果
getResult() {
return this.parsed;
}
// 格式化输出
toString() {
const { browser, os, device } = this.parsed;
return `${browser.name} ${browser.version} on ${os.fullName || os.name} (${device.type})`;
}
}
// 使用用户代理解析器
const parser = new UserAgentParser();
const result = parser.getResult();
console.group('用户代理解析结果');
console.log('浏览器:', result.browser);
console.log('渲染引擎:', result.engine);
console.log('操作系统:', result.os);
console.log('设备:', result.device);
console.log('特征:', result.features);
console.log('摘要:', parser.toString());
console.groupEnd();// 🎉 功能特性检测示例
class FeatureDetector {
constructor() {
this.features = this.detectAllFeatures();
}
// 检测所有功能特性
detectAllFeatures() {
return {
// 基础API支持
localStorage: this.hasLocalStorage(),
sessionStorage: this.hasSessionStorage(),
indexedDB: this.hasIndexedDB(),
webSQL: this.hasWebSQL(),
// 现代Web API
serviceWorker: this.hasServiceWorker(),
webWorker: this.hasWebWorker(),
sharedWorker: this.hasSharedWorker(),
// 媒体API
getUserMedia: this.hasGetUserMedia(),
webRTC: this.hasWebRTC(),
webAudio: this.hasWebAudio(),
// 图形API
canvas: this.hasCanvas(),
webGL: this.hasWebGL(),
webGL2: this.hasWebGL2(),
// 网络API
fetch: this.hasFetch(),
websocket: this.hasWebSocket(),
eventSource: this.hasEventSource(),
// 设备API
geolocation: this.hasGeolocation(),
deviceOrientation: this.hasDeviceOrientation(),
vibration: this.hasVibration(),
// 输入API
touch: this.hasTouch(),
pointer: this.hasPointer(),
gamepad: this.hasGamepad(),
// 现代JavaScript特性
es6: this.hasES6(),
modules: this.hasModules(),
asyncAwait: this.hasAsyncAwait(),
// CSS特性
cssGrid: this.hasCSSGrid(),
cssFlexbox: this.hasCSSFlexbox(),
cssCustomProperties: this.hasCSSCustomProperties()
};
}
// 存储API检测
hasLocalStorage() {
try {
const test = '__test__';
localStorage.setItem(test, test);
localStorage.removeItem(test);
return true;
} catch (e) {
return false;
}
}
hasSessionStorage() {
try {
const test = '__test__';
sessionStorage.setItem(test, test);
sessionStorage.removeItem(test);
return true;
} catch (e) {
return false;
}
}
hasIndexedDB() {
return 'indexedDB' in window;
}
hasWebSQL() {
return 'openDatabase' in window;
}
// Worker API检测
hasServiceWorker() {
return 'serviceWorker' in navigator;
}
hasWebWorker() {
return 'Worker' in window;
}
hasSharedWorker() {
return 'SharedWorker' in window;
}
// 媒体API检测
hasGetUserMedia() {
return !!(navigator.mediaDevices && navigator.mediaDevices.getUserMedia);
}
hasWebRTC() {
return 'RTCPeerConnection' in window;
}
hasWebAudio() {
return 'AudioContext' in window || 'webkitAudioContext' in window;
}
// 图形API检测
hasCanvas() {
const canvas = document.createElement('canvas');
return !!(canvas.getContext && canvas.getContext('2d'));
}
hasWebGL() {
try {
const canvas = document.createElement('canvas');
return !!(canvas.getContext('webgl') || canvas.getContext('experimental-webgl'));
} catch (e) {
return false;
}
}
hasWebGL2() {
try {
const canvas = document.createElement('canvas');
return !!canvas.getContext('webgl2');
} catch (e) {
return false;
}
}
// 网络API检测
hasFetch() {
return 'fetch' in window;
}
hasWebSocket() {
return 'WebSocket' in window;
}
hasEventSource() {
return 'EventSource' in window;
}
// 设备API检测
hasGeolocation() {
return 'geolocation' in navigator;
}
hasDeviceOrientation() {
return 'DeviceOrientationEvent' in window;
}
hasVibration() {
return 'vibrate' in navigator;
}
// 输入API检测
hasTouch() {
return 'ontouchstart' in window || navigator.maxTouchPoints > 0;
}
hasPointer() {
return 'PointerEvent' in window;
}
hasGamepad() {
return 'getGamepads' in navigator;
}
// JavaScript特性检测
hasES6() {
try {
eval('const test = () => {}; class Test {}');
return true;
} catch (e) {
return false;
}
}
hasModules() {
const script = document.createElement('script');
return 'noModule' in script;
}
hasAsyncAwait() {
try {
eval('async function test() { await Promise.resolve(); }');
return true;
} catch (e) {
return false;
}
}
// CSS特性检测
hasCSSGrid() {
return CSS.supports('display', 'grid');
}
hasCSSFlexbox() {
return CSS.supports('display', 'flex');
}
hasCSSCustomProperties() {
return CSS.supports('--custom-property', 'value');
}
// 获取功能支持报告
getReport() {
const supported = [];
const unsupported = [];
Object.entries(this.features).forEach(([feature, isSupported]) => {
if (isSupported) {
supported.push(feature);
} else {
unsupported.push(feature);
}
});
return {
supported,
unsupported,
supportRate: (supported.length / (supported.length + unsupported.length) * 100).toFixed(1)
};
}
// 检测特定功能
supports(feature) {
return this.features[feature] || false;
}
// 条件加载polyfill
async loadPolyfillsIfNeeded() {
const polyfills = [];
if (!this.supports('fetch')) {
polyfills.push('fetch');
}
if (!this.supports('es6')) {
polyfills.push('es6-shim');
}
if (!this.supports('webWorker')) {
console.warn('Web Worker不支持,某些功能可能受限');
}
// 动态加载polyfill
for (const polyfill of polyfills) {
try {
await this.loadScript(`/polyfills/${polyfill}.js`);
console.log(`已加载 ${polyfill} polyfill`);
} catch (error) {
console.error(`加载 ${polyfill} polyfill 失败:`, error);
}
}
}
// 动态加载脚本
loadScript(src) {
return new Promise((resolve, reject) => {
const script = document.createElement('script');
script.src = src;
script.onload = resolve;
script.onerror = reject;
document.head.appendChild(script);
});
}
}
// 使用功能检测器
const featureDetector = new FeatureDetector();
// 获取功能支持报告
const report = featureDetector.getReport();
console.log('功能支持报告:', report);
console.log(`支持率: ${report.supportRate}%`);
// 检测特定功能
if (featureDetector.supports('serviceWorker')) {
console.log('支持Service Worker,可以实现PWA功能');
} else {
console.log('不支持Service Worker,PWA功能受限');
}
// 条件加载polyfill
featureDetector.loadPolyfillsIfNeeded();核心应用场景:
💼 开发价值:navigator对象是实现跨浏览器兼容性的重要工具,掌握它能让你的应用在各种环境下都能正常运行
通过本节navigator对象详解的学习,你已经掌握:
A: 浏览器检测容易出错且维护困难,用户代理字符串可能被伪造;特性检测更准确,能直接检测所需功能是否可用。
A: 不要完全依赖用户代理字符串,结合特性检测和行为检测;对于关键功能,始终进行实际的功能测试。
A: platform提供操作系统平台信息,userAgent包含完整的浏览器和系统信息;platform更简洁但信息有限。
A: 结合多种方法:检查用户代理字符串、屏幕尺寸、触摸支持、设备像素比等,不要依赖单一指标。
A: navigator.onLine只能检测网络连接状态,不能检测网络质量;在某些情况下可能不准确,建议结合实际网络请求测试。
// 🎉 智能设备适配系统
class SmartDeviceAdapter {
constructor() {
this.detector = new BrowserDetector();
this.featureDetector = new FeatureDetector();
this.deviceInfo = this.analyzeDevice();
this.init();
}
// 分析设备能力
analyzeDevice() {
const browser = this.detector.detectBrowser();
const os = this.detector.detectOS();
const device = this.detector.detectDevice();
const features = this.featureDetector.features;
return {
browser,
os,
device,
features,
performance: this.estimatePerformance(),
capabilities: this.assessCapabilities()
};
}
// 估算设备性能
estimatePerformance() {
const memory = navigator.deviceMemory || 4; // 默认4GB
const cores = navigator.hardwareConcurrency || 4; // 默认4核
const connection = navigator.connection;
let score = 0;
// 内存评分
if (memory >= 8) score += 30;
else if (memory >= 4) score += 20;
else score += 10;
// CPU评分
if (cores >= 8) score += 30;
else if (cores >= 4) score += 20;
else score += 10;
// 网络评分
if (connection) {
if (connection.effectiveType === '4g') score += 20;
else if (connection.effectiveType === '3g') score += 15;
else score += 10;
} else {
score += 15; // 默认评分
}
// 设备类型调整
if (this.deviceInfo.device.type === 'mobile') score *= 0.8;
else if (this.deviceInfo.device.type === 'tablet') score *= 0.9;
return Math.min(100, score);
}
// 评估设备能力
assessCapabilities() {
const features = this.featureDetector.features;
return {
canRunPWA: features.serviceWorker && features.fetch,
canUseWebGL: features.webGL,
canUseWebRTC: features.webRTC && features.getUserMedia,
canUseOffline: features.serviceWorker && features.indexedDB,
canUseAdvancedCSS: features.cssGrid && features.cssFlexbox,
canUseModernJS: features.es6 && features.asyncAwait
};
}
// 初始化适配
init() {
this.applyDeviceOptimizations();
this.loadAppropriateResources();
this.setupEventListeners();
}
// 应用设备优化
applyDeviceOptimizations() {
const { device, performance } = this.deviceInfo;
// 根据设备类型调整界面
document.body.classList.add(`device-${device.type}`);
// 根据性能调整功能
if (performance < 50) {
document.body.classList.add('low-performance');
this.disableHeavyAnimations();
} else if (performance > 80) {
document.body.classList.add('high-performance');
this.enableAdvancedFeatures();
}
// 触摸设备优化
if (device.isTouch) {
document.body.classList.add('touch-device');
this.optimizeForTouch();
}
}
// 加载适当的资源
async loadAppropriateResources() {
const { capabilities, performance } = this.deviceInfo;
// 根据能力加载polyfill
if (!capabilities.canUseModernJS) {
await this.loadScript('/polyfills/es6.js');
}
if (!capabilities.canUseAdvancedCSS) {
await this.loadScript('/polyfills/css.js');
}
// 根据性能加载不同版本的资源
if (performance < 50) {
await this.loadScript('/js/app.lite.js');
} else {
await this.loadScript('/js/app.full.js');
}
}
// 禁用重型动画
disableHeavyAnimations() {
const style = document.createElement('style');
style.textContent = `
* {
animation-duration: 0.01ms !important;
animation-delay: 0.01ms !important;
transition-duration: 0.01ms !important;
transition-delay: 0.01ms !important;
}
`;
document.head.appendChild(style);
}
// 启用高级功能
enableAdvancedFeatures() {
// 启用高质量图形
document.body.classList.add('high-quality-graphics');
// 启用复杂动画
document.body.classList.add('advanced-animations');
}
// 触摸优化
optimizeForTouch() {
// 增大触摸目标
const style = document.createElement('style');
style.textContent = `
button, a, input, select {
min-height: 44px;
min-width: 44px;
}
`;
document.head.appendChild(style);
}
// 动态加载脚本
loadScript(src) {
return new Promise((resolve, reject) => {
const script = document.createElement('script');
script.src = src;
script.onload = resolve;
script.onerror = reject;
document.head.appendChild(script);
});
}
// 设置事件监听
setupEventListeners() {
// 监听网络状态变化
window.addEventListener('online', () => {
console.log('网络已连接');
this.handleNetworkChange(true);
});
window.addEventListener('offline', () => {
console.log('网络已断开');
this.handleNetworkChange(false);
});
// 监听设备方向变化
if ('orientation' in screen) {
screen.orientation.addEventListener('change', () => {
this.handleOrientationChange();
});
}
}
// 处理网络状态变化
handleNetworkChange(isOnline) {
document.body.classList.toggle('offline', !isOnline);
if (isOnline) {
// 恢复在线功能
this.enableOnlineFeatures();
} else {
// 启用离线模式
this.enableOfflineMode();
}
}
// 处理设备方向变化
handleOrientationChange() {
const orientation = screen.orientation.angle;
document.body.classList.toggle('landscape', Math.abs(orientation) === 90);
document.body.classList.toggle('portrait', Math.abs(orientation) !== 90);
}
// 获取设备信息报告
getDeviceReport() {
return {
...this.deviceInfo,
timestamp: new Date().toISOString(),
userAgent: navigator.userAgent
};
}
}
// 使用智能设备适配系统
const adapter = new SmartDeviceAdapter();
const report = adapter.getDeviceReport();
console.log('设备适配报告:', report);"掌握navigator对象,让你的Web应用能够智能适配各种设备和浏览器环境!这是构建高质量Web应用的关键技能。"