Get OS details from the webpage in JavaScript. 👷‍♂️
Tags: javascript, webdev, html, css
Published: 2020-09-25 12:54:07

The other day I was making a random demo app in Vue where I wanted to get the user's machine information (not for snooping) but to display the basic information like the Operating System (OS) name with version etc.

I had to confess I was so bad at this that I almost immediately revoked the idea to do such a thing. But now I think if not on Vue, I need to do this with vanilla JS. 

Taking this move further, I decided to dynamically add or delete DOM elements after detecting the OS. Though not this, we'll definitely learn how to detect the OS on both web and mobile.

---

![Windows OS GIF](https://media.giphy.com/media/hJaQNVrOPC4Ja/giphy.gif)
<figcaption>Oops!</figcaption>

---

## Detecting desktop OS (Windows/Mac/Linux)

First, let's detect whether the client's machine is running an OS that seriously needs to ramp up its application store (Windows) or the one which almost all programmers and hackers love the most (Linux) or the OS which can exclusively run XCode (Mac).

This can simply be achieved by analyzing the value of **`navigator.appVersion`** of the [`window`](https://developer.mozilla.org/en-US/docs/Web/API/Window/window) object. This one simple thing can do many things. Not only it will tell you about the current device OS (we'll see more about this below), but also, it can be used to get the version information about the browser it's currently running on.

Let's declare `detectedOS` as a variable in JS which holds the String information regarding the OS type. Next, we'll make three `if` checks (`switch` can work too).

```js
// default value just in case if nothing is detected
var detectedOS = "Unknown OS"; 
```

Inside the first check, let's use the `navigator.appVersion` to get the [index](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/indexOf) of the three major OS platforms: `Win` (Windows), `Mac` (MacOS), and `Linux`.

```js
if (navigator.appVersion.indexOf("Mac") != -1) 
	detectedOS = "MacOS";
```

Here, we check if the index value is _not equal to `1`_, then we set our variable value to "MacOS".

Similarly, we can perform the same check for the other two OS:

```js
var detectedOS = "Unknown OS";

if (navigator.appVersion.indexOf("Mac") != -1) 
	detectedOS = "MacOS";

if (navigator.appVersion.indexOf("Win") != -1) 
	detectedOS = "Windows";

if (navigator.appVersion.indexOf("Linux") != -1) 
	detectedOS = "Linux";
```

Okay, all cool but how to display the user that a specific OS has been detected? There are multiple ways to do this. One good way would be:

Adding an `alert()` which says "Device OS is: " when a button is clicked.

```js
var detectOS = "Unknown OS";

if (navigator.appVersion.indexOf("Win") != -1) 
	detectOS = "Windows";

if (navigator.appVersion.indexOf("Mac") != -1) 
	detectOS = "MacOS";

if (navigator.appVersion.indexOf("Linux") != -1) 
	detectOS = "Linux";

document.querySelector('button').addEventListener('click', detect);

function detect() {
   alert(`Device OS is: ${detectOS}`)
}
```

This is how it looks on Mac:

![Detection on Mac](https://dev-to-uploads.s3.amazonaws.com/i/plfvqkmv7l09x49zcl27.png)


On Windows:

![Detection on Windows](https://dev-to-uploads.s3.amazonaws.com/i/82031tz1231rh69dotk4.jpg)

And on Linux:

![404 image](https://images.unsplash.com/photo-1594322436404-5a0526db4d13?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=2515&q=80)
<figcaption>Sorry, I don't have a Linux machine 🙃</figcaption>


## Detecting mobile OS (Android/iOS)

With the current code, if you try to run it on mobile (via [CodePen](https://codepen.io)), you'll see the following alert:

![Android demo 1](https://dev-to-uploads.s3.amazonaws.com/i/iuxsgls4vcsem30bfp82.jpg)

While it's true that [Android is based on a _modified_ version of Linux](https://en.wikipedia.org/wiki/Android_(operating_system)), it's not entirely a Linux OS. So how do we make sure that "Android" is detected here instead of "Linux"?

This is explained by a Stackoverflow user Vladyslav Turak in the following answer:

{% stackoverflow 38241481 %}

```js
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());
```

As you can see, we are using the same `if` statement checks as before, but for Android, we are testing `/Android/.test` with the [`navigator.userAgent`](https://developer.mozilla.org/en-US/docs/Web/API/NavigatorID/userAgent). 

This is quite a nice workaround and upon running it on my Android phone, here is the result:

![Android demo](https://dev-to-uploads.s3.amazonaws.com/i/48d8ki95n9ukfdz4oa6o.jpg)

I don't have an iOS device to check for that device. You can do so and let me know below in the comments.

Note that the guy who gave the answer to this has clearly stated that:

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

---

_Thanks for reading, I appreciate it! Have a good day. (✿◕‿◕✿)_

---
<blockquote class="twitter-tweet" data-partner="tweetdeck"><p lang="en" dir="ltr">Debugging can be tough 😂<br>.<a href="https://twitter.com/hashtag/coding?src=hash&amp;ref_src=twsrc%5Etfw">#coding</a> <a href="https://twitter.com/hashtag/developer?src=hash&amp;ref_src=twsrc%5Etfw">#developer</a> <a href="https://twitter.com/hashtag/webdevelopment?src=hash&amp;ref_src=twsrc%5Etfw">#webdevelopment</a> <a href="https://twitter.com/hashtag/iosdevelopment?src=hash&amp;ref_src=twsrc%5Etfw">#iosdevelopment</a> <a href="https://twitter.com/hashtag/javadevelopment?src=hash&amp;ref_src=twsrc%5Etfw">#javadevelopment</a> <a href="https://twitter.com/hashtag/java?src=hash&amp;ref_src=twsrc%5Etfw">#java</a> <a href="https://twitter.com/hashtag/python?src=hash&amp;ref_src=twsrc%5Etfw">#python</a> <a href="https://twitter.com/hashtag/ruby?src=hash&amp;ref_src=twsrc%5Etfw">#ruby</a> <a href="https://twitter.com/hashtag/php?src=hash&amp;ref_src=twsrc%5Etfw">#php</a> <a href="https://twitter.com/hashtag/html?src=hash&amp;ref_src=twsrc%5Etfw">#html</a> <a href="https://twitter.com/hashtag/javascript?src=hash&amp;ref_src=twsrc%5Etfw">#javascript</a> <a href="https://twitter.com/hashtag/codingmeme?src=hash&amp;ref_src=twsrc%5Etfw">#codingmeme</a> <a href="https://twitter.com/hashtag/codingjoke?src=hash&amp;ref_src=twsrc%5Etfw">#codingjoke</a> <a href="https://twitter.com/hashtag/developerhumor?src=hash&amp;ref_src=twsrc%5Etfw">#developerhumor</a> <a href="https://twitter.com/hashtag/devhumor?src=hash&amp;ref_src=twsrc%5Etfw">#devhumor</a> <a href="https://twitter.com/hashtag/devhumour?src=hash&amp;ref_src=twsrc%5Etfw">#devhumour</a> <a href="https://twitter.com/hashtag/programmerhumor?src=hash&amp;ref_src=twsrc%5Etfw">#programmerhumor</a> <a href="https://twitter.com/hashtag/programmingmeme?src=hash&amp;ref_src=twsrc%5Etfw">#programmingmeme</a> <a href="https://twitter.com/hashtag/programmingjoke?src=hash&amp;ref_src=twsrc%5Etfw">#programmingjoke</a> <a href="https://twitter.com/hashtag/devlife?src=hash&amp;ref_src=twsrc%5Etfw">#devlife</a> <a href="https://twitter.com/hashtag/webdesign?src=hash&amp;ref_src=twsrc%5Etfw">#webdesign</a> <a href="https://t.co/UtkN6iuRBG">pic.twitter.com/UtkN6iuRBG</a></p>&mdash; Coding Interview Coach (@CoachCoding) <a href="https://twitter.com/CoachCoding/status/1299376340077084674?ref_src=twsrc%5Etfw">August 28, 2020</a></blockquote>
<script async src="https://platform.twitter.com/widgets.js" charset="utf-8"></script>
---

#### [📫 Subscribe to my weekly developer newsletter 📫](https://mailchi.mp/f59beeac6b9b/devupdates)

##### PS: From this year, I've decided to write here on DEV Community. Previously, I wrote on Medium. If anyone wants to take a look at my articles, [here](https://medium.com/@vaibhavkhulbe)'s my Medium profile.