-1

What is the best way to detect MacOS, iOS, Windows, Android, and Linux operating systems with JavaScript?

The answer should return the type of the OS regardless of the device. For e.g. iOS is used on iPhone, iPad and answer should return iOS as OS type.

Looking for answers which do not use the navigator.platform property since it is deprecated.

Kishan Patel
  • 509
  • 7
  • 16

1 Answers1

-1

navigator.platform is deprecated and should not be used. The below approach is based on checking the navigator.userAgent property.

Note: navigator.userAgent can be faked by the user or a browser extension, so the below function is not guaranteed to work 100%.

The below code is derived and modified from here. Unable to post an answer on that thread, so sharing it here.

function getPlatformOS() {
  const userAgent = window.navigator.userAgent;
  let os = null;

  const isIOS = (/iPad|iPhone|iPod/.test(userAgent) ||
  (/Mac|Mac OS|MacIntel/gi.test(userAgent) && (navigator.maxTouchPoints > 1 || "ontouchend" in document))) && !window.MSStream;

  if (/Macintosh|Mac|Mac OS|MacIntel|MacPPC|Mac68K/gi.test(userAgent)) {
    os = 'Mac OS';
  } else if (isIOS) {
    os = 'iOS';
  } else if (/'Win32|Win64|Windows|Windows NT|WinCE/gi.test(userAgent)) {
    os = 'Windows';
  } else if (/Android/gi.test(userAgent)) {
    os = 'Android';
  } else if (/Linux/gi.test(userAgent)) {
    os = 'Linux';
  }

  return os;
}
console.log(getPlatformOS())

Detecting the iOS is based on some of the answers from here

Kishan Patel
  • 509
  • 7
  • 16
  • "Unable to post an answer on that thread, so sharing it here" — The question was closed for a reason. You should pay attention to that reason instead of repeating the same mistake. – Quentin Sep 16 '21 at 12:45
  • @Quentin I know it's close but if I want to post the latest answer then how would I do that? – Kishan Patel Sep 16 '21 at 12:49
  • Think about *why* it was closed. – Quentin Sep 16 '21 at 12:49
  • I know it's a duplicate of other questions but my solution is separate and does not include any deprecated mehtods. – Kishan Patel Sep 16 '21 at 12:52
  • 1
    So because your answer to the same question is different, you think that you shouldn't answer the question that has been asked already but should repeat that question and then answer your own duplicate? That doesn't make sense. – Quentin Sep 16 '21 at 12:52
  • The previous questions were asked specifically for the OS version. My question and answer are not tied to that info. It's based on the type of OS regardless of the different devices. – Kishan Patel Sep 16 '21 at 13:01
  • @Quentin I've modified the question and added some more info. – Kishan Patel Sep 16 '21 at 13:07
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/237180/discussion-between-kishan-patel-and-quentin). – Kishan Patel Sep 16 '21 at 13:12