用JS检测MacOS、iOS、Windows、Android和Linux操作系统

Detect MacOS, iOS, Windows, Android and Linux OS with JS(用JS检测MacOS、iOS、Windows、Android和Linux操作系统)
本文介绍了用JS检测MacOS、iOS、Windows、Android和Linux操作系统的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

如何使用 JavaScript 检测 MacOS X、iOS、Windows、Android 和 Linux 操作系统?

How to detect MacOS X, iOS, Windows, Android and Linux operating system with JavaScript?

推荐答案

我学到了很多关于 window.navigator 对象及其属性:platform, appVersionuserAgent.在我看来,几乎不可能 100% 确定地检测到用户的操作系统,但在我的情况下,85%-90% 对我来说已经足够了.

I learnt a lot about window.navigator object and its properties: platform, appVersion and userAgent. To my mind, it's almost impossible to detect user's OS with 100% sure, but in my case 85%-90% was enough for me.

因此,在查看了大量 stackoverflows 的答案和一些文章后,我写了这样的内容:

So, after examining tons of the stackoverflows' answers and some articles, I wrote something like this:

function getOS() {
  var userAgent = window.navigator.userAgent,
      platform = window.navigator.platform,
      macosPlatforms = ['Macintosh', 'MacIntel', 'MacPPC', 'Mac68K'],
      windowsPlatforms = ['Win32', 'Win64', 'Windows', 'WinCE'],
      iosPlatforms = ['iPhone', 'iPad', 'iPod'],
      os = null;

  if (macosPlatforms.indexOf(platform) !== -1) {
    os = 'Mac OS';
  } else if (iosPlatforms.indexOf(platform) !== -1) {
    os = 'iOS';
  } else if (windowsPlatforms.indexOf(platform) !== -1) {
    os = 'Windows';
  } else if (/Android/.test(userAgent)) {
    os = 'Android';
  } else if (!os && /Linux/.test(platform)) {
    os = 'Linux';
  }

  return os;
}

alert(getOS());

灵感:

  1. 什么是navigator.platform 截至今天的可能值列表?
  2. 最佳使用 JavaScript 或 jQuery 检测 Mac OS X 或 Windows 计算机的方法
  3. 如何检测我的浏览器版本和使用 JavaScript 的操作系统?
  4. 如何检测浏览器和使用 javaScript 的操作系统名称和版本

我还使用了移动和桌面浏览器列表来测试我的代码:

Also I used the lists of mobile and desktop browsers to test my code:

  1. 所有移动浏览器列表
  2. 所有浏览器列表

此代码可以正常工作.我在所有操作系统上进行了测试:MacOS、iOS、Android、Windows 和 UNIX,但我不能保证 100% 确定.

This code works properly. I tested it on all the OS: MacOS, iOS, Android, Windows and UNIX, but I can't guarantee 100% sure.

这篇关于用JS检测MacOS、iOS、Windows、Android和Linux操作系统的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

在开发JS过程中,会经常遇到两个小数相运算的情况,但是运算结果却与预期不同,调试一下发现计算结果竟然有那么长一串尾巴。如下图所示: 产生原因: JavaScript对小数运算会先转成二进制,运算完毕再转回十进制,过程中会有丢失,不过不是所有的小数间运算会
问题描述: 在javascript中引用js代码,然后导致反斜杠丢失,发现字符串中的所有\信息丢失。比如在js中引用input type=text onkeyup=value=value.replace(/[^\d]/g,) ,结果导致正则表达式中的\丢失。 问题原因: 该字符串含有\,javascript对字符串进行了转
Rails/Javascript: How to inject rails variables into (very) simple javascript(Rails/Javascript:如何将 rails 变量注入(非常)简单的 javascript)
CoffeeScript always returns in anonymous function(CoffeeScript 总是以匿名函数返回)
Ordinals in words javascript(javascript中的序数)
getFullYear returns year before on first day of year(getFullYear 在一年的第一天返回前一年)