Vanilla JavaScript detecting the operating system

โœ๏ธ

How to detect the operating system using JavaScript

13 Nov, 2020 ยท 2 min read

I'm sure you've ever seen this in action. A website states, "Hey, you're on macOS, download this specific Mac version." Or download the Windows EXE here.

It mainly comes down to downloads, but there can be some cool advantages of knowing a user's browser and system.

In today's article, we will be using the navigator API to get the appVersion.

The result will look like this:

JavaScript detect OS version

HTML Document

For our demo, we will be created a simple card that we can render some information.

<div class="card" id="os_card"></div>

CSS Styling

Now let's make the card look more appealing by centering it and using some colors.

body {
  display: flex;
  min-height: 100vh;
  align-items: center;
  justify-content: center;
  font-family: Roboto, 'Helvetica Neue', Arial, sans-serif;
  background: #f3c4fb;
}
.card {
  background: #e2afff;
  color: #fff;
  box-shadow: 0 10px 20px 0 rgba(0, 77, 115, 0.07);
  border-radius: 10px;
  padding: 30px 40px;
  font-size: 2rem;
}

JavaScript detect Operating System

Now we can go ahead and find the user's OS!

As mentioned, we make use of the navigator API.

Let's first declare our starting variables.

const card = document.getElementById('os_card');
let os = 'Unknown';

We also define an empty OS variable if we can't find the right one.

Now we are going to check if the OS string returns something familiar.

if (navigator.appVersion.indexOf('Win') != -1) os = 'Windows';
if (navigator.appVersion.indexOf('Mac') != -1) os = 'MacOS';
if (navigator.appVersion.indexOf('X11') != -1) os = 'UNIX';
if (navigator.appVersion.indexOf('Linux') != -1) os = 'Linux';

An entire string would look something like this (MacOs)

// 5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.183 Safari/537.36

Now we are going to add our string to our card:

card.innerHTML = 'Your OS: ' + os;

That's it. See the result in this Codepen.

See the Pen Vanilla JavaScript detecting the operating system by Chris Bongers (@rebelchris) on CodePen.

Browser Support

The Navigator API has excellent support these days!

JavaScript Navigator API support

Thank you for reading, and let's connect!

Thank you for reading my blog. Feel free to subscribe to my email newsletter and connect on Facebook or Twitter

Spread the knowledge with fellow developers on Twitter
Tweet this tip
Powered by Webmentions - Learn more

Read next ๐Ÿ“–

JavaScript sending data between windows

9 Sep, 2022 ยท 4 min read

JavaScript sending data between windows

Using the native payment request JavaScript API

9 Aug, 2022 ยท 8 min read

Using the native payment request JavaScript API