How to detect the operating system of the client machine using JS
Overview
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.
Both methods mentioned above return a string, which is then used to extract the user's operating system.
Note: To refer to the official documentation of the
navigatorobject, please visit this link.
Syntax
//Syntax for the first method
navigator.appVersion
//Syntax for the second method
navgiator.userAgent
The navigator object is mainly used to represent the state and the user's identity. It is used to detect the version of the browser and the operating system of the user.
Return value
The return values for both the methods are as follows:
navigator.appVersion: It returns a string that specifies the browser version of the user.navigator.userAgent: This method returns a string that represents the browser's user agent header.
Note: The method of
navigator.appVersionis now deprecated and is not supported in many modern-day browsers, so we’ll use thenavigator.userAgentmethod to detect users’ OS.
Example
Explanation
The explanation for the code in the HTML file is given below:
- Line 7: This is a placeholder
<div>, which has theidattribute set toos, so this<div>tag will get populated by the clients' OS. - Line 8: This line of code contains an HTML
<button>with theonclickattribute, which triggers theosfunction(), which is a piece of JS code required to detect the OS.
The code in the JS file is explained as follows:
- Line 3: We use the
navigator.userAgentmethod and assign the string returned to anosvariable. - Lines 4–16: We initialize an empty string and assign it to a variable named
finalOs.Next, we decide on the users' OS by the use of conditional statements(if-else)and thesearchmethod, which searches through the string for the operating system and returns-1if the OS given in the parameter is not found. - Line 18: Finally, we use DOM and its
document.getElementById()method to populate the<div>tag in the HTML document with the clients' OS.
To explore more related to the
searchmethod provided by JS, please refer to this link.
Free Resources