Detect platform

So how do you find out what Operating System the user is using to access your web pages? We can use the navigator object as shown in the DetectPlatform () function below to learn what platform is being used to access your web page. The function returns Windows, Macintosh, or Other.

The following shows the output of the script: Your operating system: Windows

Scripting code

Step 1: place the following code in the head section (between <head> and </head>) of your web document. Note the script returns Windows, Macintosh, or other as the type of platform used to access a web page.

<script language="javascript">
function DetectPlatform () {
var platform;
// is the operating system Windows?
if(navigator.appVersion.indexOf("Win") != -1) {
platform = "Windows";// the platform is Windows
}
// Or is it Macintosh?
else if(navigator.appVersion.indexOf("Mac") != -1) {
platform = "Macintosh";// the platform is Macintosh
}
// Or is it something else?
else {
platform = "Other";// it is neither Windows nor Macintosh
}
return platform;// return the type of platform
}
</script>

In the function above, with the first conditional statement we check if the navigator object contains the string “Win.” If it does, that will indicate the platform is Windows. If, however, the navigator object contains the string “Mac,” the platform is Macintosh. If the navigator object does not contain the string “Win”, or “Mac”, the platform must be something else (i.e., UNIX, Linux, etc.).

Step 2: Call the above function (DetectPlatform()) from your web page:

<script language="javascript">
// calling the function
document.write ("Your operating system: " + DetectPlatform());
</script>

In step 2, we instruct the browser to execute the code inside DetectPlatform () function. The function returns one of the values as shown/discussed above.