Using Vanilla JS:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Browser Info</title>
</head>
<body>
<h1>Your Browser is <span id="browser"></span></h1>
<script>
var nameArray = ["Chrome", "Firefox", "Safari", "Opera", "MSIE", "Trident", "Edge"];
var bname, agent = navigator.userAgent;
for(var i = 0; i < nameArray.length; i++)
{
if(agent.indexOf(nameArray[i]) > -1)
{
bname = nameArray[i];
break;
}
}
alert("You are using " + bname);
document.getElementById("browser").innerHTML = bname;
</script>
</body>
Here a simple h1 tag consists of the text where we want to display the name of the browser.
Inside the script tags, we have three variables
- nameArray: it is an array and stores the name of the browsers
- bname, agent: it stores the name of the browser returned by navigator.userAgent.
agent.indexOf(nameArray[i]) > -1
this check the name returned by the navigator.userAgent and checks for its index in the nameArray if the name of the browser is present in the array then it stores the name of the array in the in variable bname and alerts it out telling the name of the browser. You might be wondering what is MSIE, Trident, Edge there are the different name of browser provided by Microsoft windows.
Using Bowser JavaScript library
using vanilla js we can only view the name of the browser, to view the version of the browser using the “Bowser” library we can achieve this by writing three lines of code as shown below.<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Browser Info</title>
</head>
<body>
<script src="https://unpkg.com/bowser@2.4.0/es5.js"></script>
<script>
var result = bowser.getParser(window.navigator.userAgent);
console.log(result);
document.write("You are using " + result.parsedResult.browser.name + " v" + result.parsedResult.browser.version + " on " + result.parsedResult.os.name);
</script>
</body>
</html>
Let us understand the code:
This is a simple html code with a <head> and <body> tag <body> tag consists of two <script> tags First <script> tag consists the link to the Bowser library on the internet Second script tag consists of the three lines of the javascript code where we have variable result to get and store the value returned by the bowser.getParser(window.navigator.userAgent) method. This Bowser Library has some built in methods, we are using the getParser method which has many attributes to display the name, version of the browser and name of the operating system.- result.parsedResult.browser.name: to get the browser name of the client browser
- result.parsedResult.browser.name: to get the browser version of the client browser
- result.parsedResult.os.name: to get the name of the operating system you are using.