JavaScript

How to Detect the Operating System (OS) Using JavaScript

Last updated: 24.02.2026
Views: 271

Sometimes it is necessary to determine the user’s operating system. To use different CSS styles for different OS, or for some analytics, or for other purposes. There are various plugins or libraries for detecting the operating system, but for this task you can do without a third-party plugin. If you don’t need to determine the operating system version, but only its name, then you can write the OS detection code yourself.

JavaScript

function detectOS() {
    const platform = navigator.platform.toLowerCase(),
        iosPlatforms = ['iphone', 'ipad', 'ipod', 'ipod touch'];

    if (platform.includes('mac')) return 'MacOS';
    if (iosPlatforms.includes(platform)) return 'iOS';
    if (platform.includes('win')) return 'Windows';
    if (/android/.test(navigator.userAgent.toLowerCase())) return 'Android';
    if (/linux/.test(platform)) return 'Linux';

    return 'unknown';
}

This code does not detect all the operating systems in the world, but only the main ones. I think such code will be easy to modify if there is a need to add another OS.

You can see an example of the code working on Codepen: https://codepen.io/igorrybalko/pen/vEBvPgm

author
Author: Igor Rybalko
I have been working as a front-end developer since 2014. My main technology stack is Vue.js and WordPress.

Similar posts:

  • Working with Cookies in JavaScript
    Сookie (web cookie or browser cookie) is a string of information that can be stored in a browser and sent to the server. The maximum size for one cookie is 4096 bytes. T...
  • Ways to Create Objects in JavaScript
    There are several ways to create objects in JavaScript. The Object data type plays a critical role in JS. An object is an unordered set of key-value pairs. May contain ot...
  • jQuery Accordion Plugin
    An accordion is often used on websites. This element is popular and convenient at the same time. An accordion helps to structure content and save space. In my work, I oft...

One response to “How to Detect the Operating System (OS) Using JavaScript”

  1. tlover tonet says:

    Very interesting subject, appreciate it for posting.

Leave a Reply

Your email address will not be published. Required fields are marked *