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
navigator
object, please visit this link.
//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.
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.appVersion
is now deprecated and is not supported in many modern-day browsers, so we’ll use thenavigator.userAgent
method to detect users’ OS.
The explanation for the code in the HTML file is given below:
<div>
, which has the id
attribute set to os
, so this <div>
tag will get populated by the clients' OS.<button>
with the onclick
attribute, which triggers the osfunction()
, which is a piece of JS code required to detect the OS.The code in the JS file is explained as follows:
navigator.userAgent
method and assign the string returned to an os
variable.finalOs
.Next, we decide on the users' OS by the use of conditional statements (if-else)
and the search
method, which searches through the string for the operating system and returns -1
if the OS given in the parameter is not found. document.getElementById()
method to populate the <div>
tag in the HTML document with the clients' OS.To explore more related to the
search
method provided by JS, please refer to this link.
Free Resources