How to detect operation system using Javascript

Every browser which supports Javascript has a navigator object. This is a system object with navigator.userAgent property which contains full information about user's browser and their platform.

For detecting we need to check this property and show detected OS. The best practice for that - using regular expressions.

This is just a small Javascript that displays visitors operating system on a website.

Put in your document between BODY tags following:

<div id="operation_system"></div>
<script type="text/javascript">
var regtest = {
	"Windows 3.11" :  /win16/ ,
	"Windows 95" :  /windows 95/ ,
	"Windows 95" :  /windows_95/ ,
	"Windows 95" :  /win95/ ,
	"Windows 98" :  /windows 98/ ,
	"Windows 98" :  /win98/ ,
	"Windows Me" :  /windows me/ ,
	"Windows 2k" :  /windows nt 5.0/ ,
	"Windows XP" :  /windows nt 5.1/ ,
	"Windows XP x64" :  /windows nt 5.2/ ,
	"Windows Vista" :  /windows nt 6.0/ ,
	"Windows 7" :  /windows nt 6.1/ ,
	"Windows 8" :  /windows nt 6.2/ ,
	"Windows NT 4.0" : /windows nt 4.0/,
	"Windows NT 4.0" : /winnt4.0/,
	"Windows NT 4.0" : /winnt/,
	"Windows NT 4.0" : /windows nt/,
	"Windows Phone" :  /windows phone/ ,
	"Mac OS" :  /mac/ ,
	"Mac OS" :  /powerpc/ ,
	"Mac OS" :  /macintosh/ ,
	"Linux" :  /linux/ ,
	"Linux" :  /x11/ ,
	"Ubuntu" :  /ubuntu/ ,
	"Android" : /android/ ,
	"iOS" : /iphone/ ,
	"iOS" : /ipad/ ,
	"iOS" : /ipod/ ,
	"Symbian" : /symbian/ ,
	"Meego" : /meego/ ,
	"Maemo" : /maemo/ ,
	"Sailfish OS" : /sailfish/ ,
	"QNX" :  /qnx/ ,
	"BeOS" :  /beos/ ,
	"Open BSD" :  /openbsd/ ,
	"Free BSD" :  /freebsd/ ,
	"OS/2" :  /os\/2/ ,
	"Solaris" :  /sunos/ ,
}

for(var obj in regtest) {
	if (regtest[obj].test(navigator.userAgent.toLowerCase())) {
		document.getElementById('operation_system').innerHTML = obj;
		break;
	}
}
</script>

Javascript provides RegExp object, but we can create it dynamically from a string. Next stop - I define object regtest with values containing RegExp objects. After that I iterate over properties regtest and apply their values for testing navigator.userAgent until applying will be successful. In that case I display OS and break cycle for economy resources.

There is no jQuery or other 3rd-party frameworks and libraries. You can use this code freely.

Comments:

You can left first comment.

For commenting you should proceed to enter or register on the site.