In this tutorial, you will learn how to Detect operating systems and browsers using JavaScript.
Detect the operating system and browsers using JavaScript
let’s understand it with a code explanation.
let browserDetailsRef = document.getElementById("browser-details");
let osDetailsRef = document.getElementById("os-details");
var browserList = [
{ name: "Firefox", value: "Firefox" },
{ name: "Opera", value: "OPR" },
{ name: "Edge", value: "Edg" },
{ name: "Chrome", value: "Chrome" },
{ name: "Safari", value: "Safari" },
];
var os = [
{ name: "Android", value: "Android" },
{ name: "iPhone", value: "iPhone" },
{ name: "iPad", value: "Mac" },
{ name: "Macintosh", value: "Mac" },
{ name: "Linux", value: "Linux" },
{ name: "Windows", value: "Win" },
];
let broswerChecker = () => {
//Useragent contains browser details and OS details but we need to separate them
let userDetails = navigator.userAgent;
for (let i in browserList) {
//check if the string contains any value from the array
if (userDetails.includes(browserList[i].value)) {
//extract browser name and version from the string
browserDetailsRef.innerHTML = browserList[i].name || "Unknown Browser";
break;
}
}
for (let i in os) {
//check if string contains any value from the object
if (userDetails.includes(os[i].value)) {
//displau name of OS from the object
osDetailsRef.innerHTML = os[i].name;
break;
}
}
};
window.onload = broswerChecker();
This JavaScript Code Is Designed To Extract And Display The User’s Browser and OS details by parsing ”navigator.userAgent”.
- ‘browserDetailsRef’’ and ‘osDetailsRef’’ are variables that are use to reference HTML element by IDs ‘browserDetails’ and ‘osDetails’. In this element browser and OS information displayed.
- ‘browserList’ is an Array containing object that represent various browsers. Each object has a ‘name’ and a ‘value’ property.
- ‘OS’ is an Array representing different operating system. It also has a ‘name’ and a ‘value’ property.
- ‘broswerChecker’ this is an arrow function that checks the ”navigator.userAgent” to determine the user’s browser and OS.
- At first it initialize ‘userDetails’ with ”navigator.userAgent”.
- Then it iterate over ‘browserList’ and ‘OS’ Array using ‘for’ loop.
- For each browser in ‘browserList’ it checks if the ‘userDetailsRef’ include the browser’s ‘value’. If it present then it update the ‘browserDetailsRef’ with the browser’s ‘name’ .
- Similarly it do the same thing for the ‘OS’. while found the ‘value’ it update the ‘browserDetailsRef’ with the OS ‘name’ .
- Both loop has a ‘break’ statement to exit the loop once a match is found.
- ‘window.onload’ this Event is activate the ‘broswerChecker’ function when the window finish loading. It ensure that the checking is start after the window fully loaded.