Last active
October 25, 2021 04:39
-
-
Save kanthvallampati/e9ac78f5c8d7f20667a8db16fe8ae5c4 to your computer and use it in GitHub Desktop.
JavaScript snippet to detect the user operating system
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function detectOs() { | |
let userAgt = navigator.userAgent; | |
let os = ''; | |
let version = ''; | |
let regOsVersion = ''; | |
let osMap = [ | |
{ s : 'Windows', r:/(Windows 10.0|Windows NT 10.0|Windows 8.1|Windows NT 6.3|Windows 8|Windows NT 6.2|Windows 7|Windows NT 6.1)/}, | |
{ s : 'Linux', r:/(Linux|X11(?!.*CrOS))/}, | |
{ s : 'Mac OS X', r:/Mac OS X/}, | |
{ s : 'Mac OS', r:/(Mac OS|MacPPC|MacIntel|Mac_PowerPC|Macintosh)/} | |
]; | |
for (let id in osMap) { | |
let cs = osMap[id]; | |
if (cs.r.test(userAgt)) { | |
os = cs.s; | |
regOsVersion = cs.r; | |
break; | |
} | |
} | |
switch(os) { | |
case 'Windows': | |
if (regOsVersion.exec(userAgt)[0].indexOf('NT 10.0') || regOsVersion.exec(userAgt)[0].indexOf('10.0') ) { | |
version = '10'; | |
} else if (regOsVersion.exec(userAgt)[0].indexOf('8.1') || regOsVersion.exec(userAgt)[0].indexOf('NT 6.3')) { | |
version = '8.1'; | |
} else if (regOsVersion.exec(userAgt)[0].indexOf('8') || regOsVersion.exec(userAgt)[0].indexOf('NT 6.2')) { | |
version = '8'; | |
} else if (regOsVersion.exec(userAgt)[0].indexOf('7') || regOsVersion.exec(userAgt)[0].indexOf('NT 6.1')) { | |
version = '7'; | |
} | |
break; | |
case 'Mac OS X': | |
version = userAgt.split('Mac OS X ')[1].split(')')[0]; | |
version = version.split(';')[0].replaceAll('_', '.'); | |
break; | |
case 'Mac OS': | |
version = ''; | |
break; | |
case 'Linux': | |
version = ''; | |
break; | |
} | |
return os + ' ' + version; | |
}; | |
detectOs(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment