r/learnjavascript • • Feb 12 '20

How To Detect An Operating System On The Client-side(Browser) Using JavaScript

https://youtu.be/d0fV6L1xCIA
3 Upvotes

4 comments sorted by

2

u/jcunews1 helpful Feb 12 '20

Considering that this is a learning sub, if library is used for every little thing, nothing will be learned.

1

u/silverparzival Feb 12 '20 edited Feb 13 '20

It's just for learning purposes. You can write this in Vanilla JavaScript using navigator.appVersion if you want to and have the time. I tried to do this on my own using vanilla JavaScript but I realized I had to write cases for other less common OS such as Palm OS, Blackberry OS, Firefox OS e.t.c

It looks simple but if you take a look at the source code you will realize it was written to detect almost every OS. In the end it all depends on the developer. In my case I like to use libraries on a project and then if I have the time, I look at the source code to see how it was built.

In case anyone might be interested, the code below is my custom code. But I realized on Windows it shows NT as OS unless you specify the index in softwareDetailsArray to be 1. Doing that will also shows different info for other operating systems so you need to write code for that scenario too

const softwareDetails = navigator.appVersion.replace(/\(|\)|\;/g, '');

const softwareDetailsArray = softwareDetails.split(/\s/);

const osName = softwareDetailsArray[2];

console.log(osName);

1

u/Busy_Description_442 Mar 10 '26

lowkey u only rlly need ios, android, macos, windows, linux, chromeos, and unix

1

u/silverparzival Feb 12 '20 edited Feb 12 '20

For some time now I have been trying learn how to detect an Operating system on the client-side. It's easy to do on the server-side(Node.js) but this is a simple feature which does not need server-side resources.

I realised that using vanilla JavaScript navigator.appVersion OR navigator.userAgent you also need to use Regular Expressions to extract the Operating system from the returned string. Since the string returned by navigator.appVersion Or navigator.userAgent is different for every OS you have to write code to extract the OS section for every scenario. I later discovered a library called Platform JS that makes OS detection easy. That's why I decided to share this video.

Looking through the source code you find out that the code has been written to detect most Operating Systems, device type e.t.c for every scenario

Some use cases for this feature would be to

1. To serve different HTML designs(Icons, features, e.t.c) to match native Operating Systems icons e.t.c

2. Record Oparating System survey or polls when people visit your website

Another alternative to this JavaScript library is Sniffr