Detect Operating System with JavaScript


Here’s a snippet of JS code that might come in handy if you, let’s say, would like to filter out what type of content to display depending on your website user’s OS. A real-life example would be having a download link show up to user’s who have a client that was only published on Windows.

// This script sets OSName variable as follows:
// "Windows"    for all versions of Windows
// "MacOS"      for all versions of Macintosh OS
// "Linux"      for all versions of Linux
// "UNIX"       for all other UNIX flavors 
// "Unknown OS" indicates failure to detect the OS

var OSName="Unknown OS";
if (navigator.appVersion.indexOf("Win")!=-1) OSName="Windows";
if (navigator.appVersion.indexOf("Mac")!=-1) OSName="MacOS";
if (navigator.appVersion.indexOf("X11")!=-1) OSName="UNIX";
if (navigator.appVersion.indexOf("Linux")!=-1) OSName="Linux";

document.write('Your OS: '+OSName);

Note: An alternate way can be found via PPK‘s quirksmode.org