How to determine OS in browser

Use modern APIs to retrieve information about the host system of your web app

Detect host system in browser

If you’re writing a Progressive Web App and want to determine what kind of system is hosting the agent, a simple API can help you out.

I’m explicitly only targeting modern web apps with the code in this article. Detection of the OS or browser version was notoriously fragile in the past, so the new APIs that are available on the “navigator” provide a robust solution for such tasks, yet are only available in modern browsers.

Checking the platform

The following code shows you how to reliably determine the environment via Javascript. It accesses the “navigator”, an object available on the window that provides a whole set of APIs to progressively enhance your web app.

 * Retrieve the host platform in a 
 * best-effort way w/ normalized output.
export function getAgentSystem(){
  if(!("navigator" in window)){
    return "unknown";
  // Use the modern 'web hints' provied by
  // 'userAgentData' if available, else use
  // the deprecated 'platform' as fallback.
  const platform = (navigator.userAgentData?.platform || navigator.platform)?.toLowerCase();
 if(platform.startsWith("win")) return "windows";
 if(platform.startsWith("mac")) return "macos";
 if(platform.startsWith("linux")) return "linux";
 return "unknown";

// Just to give you an idea, the following properites
// are options for the legacy 'navigator.platform':
// HP-UX
// Linux i686
// Linux armv7l
// Mac68K
// MacPPC
// MacIntel
// SunOS
// Win16
// Win32
// WebTV OS

As you can see, the logic to determine what kind of system is hosting your application is very straightforward and only requires a few lines of code.

Examples for use cases

A common use case for determining the host’s OS is to provide different keyboard shorts and subsequently “kbd”-tags in your code. For example, macOS uses the “Command”-key, whereas Windows and Linux use the “Control”-key for a lot of shortcuts.

You could also alter the styling of your UI to better align with the native UI from the host system, just to name another example.