To determine operating system on the client machine, we can make use of navigator.appVersion or navigator.userAgent.
Example To Get Operating System using JavaScript
The following example demonstrates detection of operating system on the client machine.
<!DOCTYPE html> <head> <title>OS Detection</title> </head> <body> <script type="text/javascript"> var OS_Name = navigator.appVersion; if (OS_Name.indexOf("Win") != -1) { document.write("Windows Operating System "); } else if (OS_Name.indexOf("Mac") != -1) { document.write("Mac Operating System "); } else if (OS_Name.indexOf("X11") != -1) { document.write("Unix Operating System "); } else if (OS_Name.indexOf("Linux") != -1) { document.write("Linux Operating System "); } else if (OS_Name.indexOf("SunOS") != -1) { document.write("Solaris Operating System "); } else { document.write("Unknown Operation System "); } </script> </body> </html>
- <script type=”text/javascript”> tag is used to define client side script which uses attribute type for specifying MIME type.
- Navigator object used to display information about operating system using appVersion property which returns version information of the OS.
- var OS_Name = navigator.appVersion; line specifies navigator object using appVersion property to determine os of the client machine.
- if (OS_Name.indexOf(“Win”) != -1) { document.write(“Windows Operating System “);} line contains indexOf which refers to method on collection such as dictionary, hash table etc and when collection doesn’t include Windows Operating System” it returns -1 value and this is same for above different operating systems.
- Above program keep compares with collections as mentioned in the above point. If it doesn’t matches then it returns particular OS name on the client system.
- If it didn’t find any operating system, then it displays unknown operating system.
How To Check Operating System using JavaScript Demo
- Save the file as OS_detection.html in your system.
- Just open the file in the browser, you will see the below picture in the browser. Note that the browser must support HTML specification.