JavaScript

How to Detect the Operating System (OS) Using JavaScript

Last updated: 02.04.2026
Views: 588

Sometimes it is necessary to detect the user’s operating system when building web applications or websites. This can be useful for applying different CSS styles, collecting analytics data, or adapting certain features depending on the user’s environment. While there are many libraries and plugins available for OS detection, in simple cases it is вполне possible to implement this functionality without any third-party tools.

In most situations, you do not need to detect the exact version of the operating system — knowing its general type is enough. The most common operating systems you may want to handle are Windows, macOS, Linux, Android, and iOS. These platforms cover the majority of users and are usually sufficient for practical frontend tasks.

There are several real-world use cases for detecting the operating system. For example, you may want to display different download links depending on whether the user is on Windows or macOS. Another common scenario is adjusting UI behavior or showing platform-specific instructions. In some cases, OS detection can also be used to improve user experience by tailoring content or functionality to match the user’s device.

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';
}

The approach described here does not aim to cover every possible operating system, but focuses on the most widely used ones. At the same time, the logic can be easily extended or modified if you need to support additional platforms in the future.

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:

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 *

Blue Captcha Image
Refresh

*