62

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

0

1 Answer 1

220

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 Stack Overflow answers and some articles, I wrote something like this:

function getOS() {
  const userAgent = window.navigator.userAgent,
      platform = window.navigator?.userAgentData?.platform || window.navigator.platform,
      macosPlatforms = ['macOS', 'Macintosh', 'MacIntel', 'MacPPC', 'Mac68K'],
      windowsPlatforms = ['Win32', 'Win64', 'Windows', 'WinCE'],
      iosPlatforms = ['iPhone', 'iPad', 'iPod'];
  let 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.

Sign up to request clarification or add additional context in comments.

11 Comments

Why not just use "Mac" for MacOS? Should be more future proof.
You should add "darwin" to macosPlatforms
Why do you say "I've wrote something like this" ? I wonder what the actual code do you use and why does it differ from the one here.
iosPlatforms.indexOf(platform) !== -1 Can be written more distinctly as iosPlatforms.includes(platform). It also looks like you could use string matching instead to be more generic platform.toLowerCase.startsWith("win"). You can also eliminate mutating variables by using return in each if conditions (return 'Windows' ).
Isn't time to update this since "navigator.platform" is deprecated? developer.mozilla.org/en-US/docs/Web/API/NavigatorID/platform
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.