浏览器js如何获取系统信息?
1. 使用 navigator
对象
navigator
对象提供了浏览器和操作系统的基础信息:
// 操作系统和浏览器信息
const systemInfo = {
userAgent: navigator.userAgent, // 包含操作系统和浏览器版本(但可能被篡改)
platform: navigator.platform, // 操作系统架构(如 "Win32", "MacIntel")
language: navigator.language, // 浏览器语言
hardwareConcurrency: navigator.hardwareConcurrency, // CPU 核心数
deviceMemory: navigator.deviceMemory, // 内存大小(GB,仅限 HTTPS)
};
console.log(systemInfo);
2. 屏幕信息(screen
对象)
const screenInfo = {
width: screen.width, // 屏幕宽度
height: screen.height, // 屏幕高度
colorDepth: screen.colorDepth, // 颜色位数
orientation: screen.orientation?.type, // 屏幕方向(如 "landscape")
};
3. 网络信息(navigator.connection
)
通过 Network Information API 获取网络状态(需 HTTPS):
const networkInfo = {
effectiveType: navigator.connection?.effectiveType, // 网络类型(如 "4g")
downlink: navigator.connection?.downlink, // 下行速度(Mbps)
rtt: navigator.connection?.rtt, // 延迟(毫秒)
};
4. 电池状态(navigator.getBattery()
)
异步获取设备电池信息(需用户授权):
navigator.getBattery().then(battery => {
console.log({
level: battery.level * 100 + '%', // 电量百分比
charging: battery.charging, // 是否在充电
});
});
5. WebGL 渲染器信息(通过 WebGL API)
获取 GPU 渲染器信息(可能被伪造):
const canvas = document.createElement('canvas');
const gl = canvas.getContext('webgl');
if (gl) {
const debugInfo = gl.getExtension('WEBGL_debug_renderer_info');
const gpuInfo = {
vendor: gl.getParameter(debugInfo.UNMASKED_VENDOR_WEBGL),
renderer: gl.getParameter(debugInfo.UNMASKED_RENDERER_WEBGL),
};
console.log(gpuInfo);
}
6. 时区和地理位置
- 时区:
const timezone = Intl.DateTimeFormat().resolvedOptions().timeZone;
- 地理位置(需用户授权):
navigator.geolocation.getCurrentPosition(pos => { console.log(pos.coords.latitude, pos.coords.longitude); });
注意事项
- 隐私限制:浏览器会限制敏感信息(如完整硬件信息),部分 API 需要 HTTPS 或用户授权。
- 数据可靠性:
userAgent
等字段可被篡改,不适合用于安全验证。 - 跨浏览器差异:不同浏览器支持的 API 可能不同(如
deviceMemory
仅限 Chrome)。
完整示例
async function getSystemInfo() {
return {
navigator: {
userAgent: navigator.userAgent,
platform: navigator.platform,
language: navigator.language,
hardwareConcurrency: navigator.hardwareConcurrency,
deviceMemory: navigator.deviceMemory,
},
screen: {
width: screen.width,
height: screen.height,
colorDepth: screen.colorDepth,
},
network: navigator.connection ? {
effectiveType: navigator.connection.effectiveType,
downlink: navigator.connection.downlink,
} : null,
battery: await navigator.getBattery?.().catch(() => null),
timezone: Intl.DateTimeFormat().resolvedOptions().timeZone,
};
}
getSystemInfo().then(console.log);
如果需要更详细的系统信息(如 CPU 型号、磁盘空间等),浏览器环境无法直接获取,通常需要依赖后端或原生应用(如 Electron)。