DEV Community

Nikesh Kumar T K
Nikesh Kumar T K

Posted on

Detect Operating System using javascript.

Detecting the operating system of the user is crucial if you are developing a website for any tools or software. So that you can provide recommendations of software that suits the user's operating system which can be windows, mac, or Linux.

Javascript is efficient enough to do this for us. We can make use of the javascript navigator object to access the details of a user. The navigator object has a function called userAgent that returns a string that consists of details about the user's system.


let os = navigator.userAgent;
console.log(os);

Enter fullscreen mode Exit fullscreen mode

The output of above code is

Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/108.0.0.0 Safari/537.36

To determine the type of os,we have to check wheather the returned string contains the name of the os at any index position.To ensure this we can call indexOf method on returned string

let os = navigator.userAgent.indexOf("Windows");
console.log(os);

Enter fullscreen mode Exit fullscreen mode

The output of above code is 13 since index of the word Windows is at 13 position in returned string.

This same method can be implemented to detect any operating system which will help you to provide better user experience

Top comments (1)

Collapse
 
nikeshkumartk profile image
Nikesh Kumar T K

Comment me if you found this helpful