Lets create a JavaScript function named detectBrowser()
. This function will analyze the navigator.userAgent
string, which contains information about the user's browser, operating system, and other details. We'll search for specific strings indicative of popular browsers such as Chrome, Firefox, Safari, Edge, Opera, and Internet Explorer.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Browser Detection</title>
</head>
<body>
<script>
// Function to detect the browser name
function detectBrowser() {
var userAgent = navigator.userAgent;
if (userAgent.indexOf("Edg") > -1) {
return "Microsoft Edge";
} else if (userAgent.indexOf("Chrome") > -1) {
return "Chrome";
} else if (userAgent.indexOf("Firefox") > -1) {
return "Firefox";
} else if (userAgent.indexOf("Safari") > -1) {
return "Safari";
} else if (userAgent.indexOf("Opera") > -1) {
return "Opera";
} else if (userAgent.indexOf("Trident") > -1 || userAgent.indexOf("MSIE") > -1) {
return "Internet Explorer";
}
return "Unknown";
}
// Get the browser name and display it
var browserName = detectBrowser();
document.write("Your browser is: " + browserName);
</script>
</body>
</html>
Explanation:
- The
detectBrowser()
function retrieves thenavigator.userAgent
string. - It checks for specific substrings indicative of various browsers using conditional statements.
- If a match is found, the function returns the corresponding browser name.
- If no match is found, it returns “Unknown”.