JavaScript : Detect Browser

By | November 3, 2014

In this post we will know how to know on which browser the application is running. In some real time cases we need to add the code depending on the browser compatibility in such cases we can use the below java script code to detect browser and add our code.

We need to add the below java script code in the html.

function detectBrowser(){
  var val = navigator.userAgent.toLowerCase();
  if(val.indexOf("firefox") > -1){
	alert("Mozilla Firefox")
  }else if(val.indexOf("chrome") > -1){
	alert("Google Chrome")
  }else if(val.indexOf("opera") > -1){
	alert("Opera.")
  }else if(val.indexOf("msie") > -1){
	alert("Internet Explorer")
  }else if(val.indexOf("safari") > -1){
	alert("Safari")
  }
};

In the above code snippet the navigator.userAgent will returns the value of the user-agent header sent by the browser to the server.
The value returned, contains information about the name, version and platform of the browser.

For Example :- 

It will return the value shown below for Mozilla firefox browser.

mozilla/5.0 (windows nt 6.1; rv:30.0) gecko/20100101 firefox/30.0 

Sample HTML to test the above code is shown below :

<html>
 <head>
   <script>
      function detectBrowser(){
         var val = navigator.userAgent.toLowerCase();
         console.log(val);
         if(val.indexOf("firefox") > -1){
           alert("Mozilla Firefox")
         }else if(val.indexOf("chrome") > -1){
           alert("Google Chrome")
         }else if(val.indexOf("opera") > -1){
           alert("Opera")
         }else if(val.indexOf("msie") > -1){
           alert("Internet Explorer")
         }else if(val.indexOf("safari") > -1){
           alert("Safari")
         }
      };
      window.onload=detectBrowser();
   </script>
</head>
<body>
 Hello World....!
</body>
</html>

An alert will be displayed first with the browser name.

In IE :

Internet Explorer

In FF:

Mozilla Firefox

In Chrome:

Google Chrome

Leave a Reply

Your email address will not be published. Required fields are marked *