Detect MacOS, iOS, Windows, Android and Linux OS with JS [duplicate]

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.

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?.userAgentData?.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 (/Linux/.test(platform)) {
    os="Linux";
  }

  return os;
}

alert(getOS());

Inspiration:

  1. What is the list of possible values for navigator.platform as of today?
  2. Best way to detect Mac OS X or Windows computers with JavaScript or jQuery
  3. How to detect my browser version and operating system using JavaScript?
  4. How to detect Browser and Operating System Name and Version using javaScript

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

  1. List of all Mobile Browsers
  2. List of all Browsers

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

Leave a Comment