现代浏览器提供了一组与页面执行环境相关的信息,包括浏览器、操作系统、硬件和周边设备信息。 这些属性可以通过暴露在 window.navigator 上的一组 API 获得。不过,这些 API 的跨浏览器支持还 不够好,远未达到标准化的程度。
识别浏览器与操作系统
特性检测和用户代理字符串解析是当前常用的两种识别浏览器的方式。而 navigator 和 screen
对象也提供了关于页面所在软件环境的信息。
1. navigator.oscpu
navigator.oscpu 属性是一个字符串,通常对应用户代理字符串中操作系统/系统架构相关信息。
根据 HTML 实时标准:
oscpu 属性的获取方法必须返回空字符串或者表示浏览器所在平台的字符串,比如"Windows
NT 10.0; Win64; x64"或"Linux x86_64"。
比如,Windows 10 上的 Firefox 的 oscpu 属性应该对应于以下加粗的部分:
console.log(navigator.userAgent);
“Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:58.0) Gecko/20100101 Firefox/58.0” console.log(navigator.oscpu);
“Windows NT 10.0; Win64; x64”
2. navigator.vendor
navigator.vendor 属性是一个字符串,通常包含浏览器开发商信息。返回这个字符串是浏览器
navigator 兼容模式的一个功能。根据 HTML 实时标准:
navigator.vendor 返回一个空字符串,也可能返回字符串"Apple Computer, Inc."
或字符串"Google Inc."。
例如,Chrome 中的这个 navigator.vendor 属性返回下面的字符串:
console.log(navigator.vendor); // “Google Inc.”
3. navigator.platform
navigator.platform 属性是一个字符串,通常表示浏览器所在的操作系统。根据 HTML 实时标准:
console.log(navigator.platform); // “Win32” 2
“Win32”、“FreeBSD i386"或"WebTV OS”。
例如,Windows 系统下 Chrome 中的这个 navigator.platform 属性返回下面的字符串:
4. screen.colorDepth
和 screen.pixelDepth screen.colorDepth和screen.pixelDepth返回一样的值,即显示器每像素颜色的位深。根据
CSS 对象模型(CSSOM)规范:
screen.colorDepth 和 screen.pixelDepth 属性应该返回输出设备中每像素用于显示
portrait-primary
portrait-secondary 7 landscape-primary
landscape-secondary
例如,在 Chrome 移动版中,screen.orientation 返回的信息如下:
颜色的位数,不包含 alpha 通道。 Chrome 中这两个属性的值如下所示:
console.log(screen.colorDepth); // 24
console.log(screen.pixelDepth); // 24
5. screen.orientation
screen.orientation 属性返回一个 ScreenOrientation 对象,其中包含 Screen Orientation API
定义的屏幕信息。这里面最有意思的属性是 angle 和 type,前者返回相对于默认状态下屏幕的角度, 后者返回以下 4 种枚举值之一: