How to detect MacOS X, iOS, Windows, Android and Linux operating system with JavaScript?
To detect the client machine's operating system, we can use the navigator object provided by JavaScript. The navigator object provides us with methods such as navigator. appVersion & navigator. userAgent to help us achieve our goal.
os() === "iOS") { button. value = "Download for iOS"; } else if (type. os() === "AndroidOS") { button. value = "Download for Android"; } else if (type.
To detect the operating system on the client machine, one can simply use navigator. appVersion or navigator. userAgent property. The Navigator appVersion property is a read-only property and it returns a string which represents the version information of the browser.
On your device, go to the Home screen (the one with all the icons), and tap on the Settings icon. Scroll down and tap on About phone or About tablet. Some information will appear. If one of the lines of information says Android with a version number, you have an Android device.
I learnt a lot about window.navigator
object and its properties: platform
, appVersion
and userAgent
. To my mind, it's almost impossible to detect user's OS with 100% sure, but in my case 85%-90% was enough for me.
So, after examining tons of the stackoverflows' answers and some articles, I wrote something like this:
function getOS() { var userAgent = window.navigator.userAgent, platform = window.navigator?.userAgentData?.platform ?? window.navigator.platform, macosPlatforms = ['Macintosh', 'MacIntel', 'MacPPC', 'Mac68K'], windowsPlatforms = ['Win32', 'Win64', 'Windows', 'WinCE'], iosPlatforms = ['iPhone', 'iPad', 'iPod'], os = null; if (macosPlatforms.indexOf(platform) !== -1) { os = 'Mac OS'; } else if (iosPlatforms.indexOf(platform) !== -1) { os = 'iOS'; } else if (windowsPlatforms.indexOf(platform) !== -1) { os = 'Windows'; } else if (/Android/.test(userAgent)) { os = 'Android'; } else if (!os && /Linux/.test(platform)) { os = 'Linux'; } return os; } alert(getOS());
Inspiration:
Also I used the lists of mobile and desktop browsers to test my code:
This code works properly. I tested it on all the OS: MacOS, iOS, Android, Windows and UNIX, but I can't guarantee 100% sure.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With