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.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:
- What is the list of possible values for navigator.platform as of today?
- Best way to detect Mac OS X or Windows computers with JavaScript or jQuery
- How to detect my browser version and operating system using JavaScript?
- How to detect Browser and Operating System Name and Version using javaScript
Also I used the lists of mobile and desktop browsers to test my code:
- List of all Mobile Browsers
- List of all Browsers
This code works properly. I tested it on all the OS: MacOS, iOS, Android, Windows and UNIX, but I can't guarantee 100% sure.