Detecting a User's Operating System with JavaScript

In this short article, you'll learn how to use JavaScript to determine which operating system (OS) a user is running on their device.

The navigator Object

JavaScript provides a built-in object called navigator that contains information about the user's browser and operating system.

Here's how to grab it operating system data:

const userOS = navigator.platform;
console.log(userOS); // For me it was "MacIntel"

The navigator.platform property returns a string that represents the OS of the user. For example, it could return values like "Win32", "Linux", or "MacIntel".

Writing a Function to Identify the OS

Now, let's write a simple function to categorize the common operating systems based on the value of navigator.platform. You can expand it to fit your needs:

Code Example:

function getUserOS() {
    const platform = navigator.platform;
    let osName = "Unknown OS";

    if (platform.includes("Win")) { 
        osName = "Windows";
    } else if (platform.includes("Mac")) { 
        osName = "MacOS";
    } else if (platform.includes("X11") || platform.includes("Linux")) { 
        osName = "Linux";
    }

    return osName;
}

Now you can use the getUserOS function to detect the user's OS.

Code Example:

var operatingSystem = getUserOS();
console.log("The user's operating system is: " + operatingSystem);

That's it!

Happy coding! 🦾

JSJavaScript
Avatar for Niall Maher

Written by Niall Maher

Founder of Codú - The web developer community! I've worked in nearly every corner of technology businesses: Lead Developer, Software Architect, Product Manager, CTO, and now happily a Founder.

Loading

Fetching comments

Hey! 👋

Got something to say?

or to leave a comment.