Skip to content

User Agent JavaScript detection | Code

  • by

Use the navigator userAgent property to detect User Agent in JavaScript. You have to match with the browser name to identify the user browser.

User Agent JavaScript detection

A simple example code calls this JS function on page load, and this will display the user browser name on page load.

<!DOCTYPE html>
<html lang="en">
<body>
  <script>

   function fnBrowserDetect(){

     let userAgent = navigator.userAgent;
     let browserName;

     if(userAgent.match(/chrome|chromium|crios/i)){
       browserName = "chrome";
     }else if(userAgent.match(/firefox|fxios/i)){
       browserName = "firefox";
     }  else if(userAgent.match(/safari/i)){
       browserName = "safari";
     }else if(userAgent.match(/opr\//i)){
       browserName = "opera";
     } else if(userAgent.match(/edg/i)){
       browserName = "edge";
     }else{
       browserName="No browser detection";
     }

     console.log("You are using ", browserName);         
   }
   fnBrowserDetect()
 </script>
</body>
</html>

Output:

User Agent JavaScript detection

Using navigator.userAgent with indexof to figure out the browser name.

var browserName = (function (agent) {        
     switch (true) {
            case agent.indexOf("edge") > -1: return "MS Edge";
            case agent.indexOf("edg/") > -1: return "Edge ( chromium based)";
            case agent.indexOf("opr") > -1 && !!window.opr: return "Opera";
            case agent.indexOf("chrome") > -1 && !!window.chrome: return "Chrome";
            case agent.indexOf("trident") > -1: return "MS IE";
            case agent.indexOf("firefox") > -1: return "Mozilla Firefox";
            case agent.indexOf("safari") > -1: return "Safari";
            default: return "other";
        }
    })(window.navigator.userAgent.toLowerCase());

document.querySelector("h1").innerText="You are using "+ browserName +" browser";  

Do comment if you have any doubts or suggestions on this js code.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

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