Skip to content

User Agent JavaScript detection | Code

  • by

Use the navigator userAgent property to detect User Agent in JavaScript. You have to match 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

We use 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";  
  1. Accessing the User Agent String:
    • navigator.userAgent retrieves the user agent string, which contains information about the browser, version, and operating system.
  2. Displaying the User Agent String:
    • The user agent string is displayed in a paragraph element with the id userAgent.
  3. Detecting the Browser:
    • A simple check using indexOf to see if the user agent string contains certain substrings like "Chrome", "Firefox", "Safari", "MSIE", or "Trident".
    • Depending on the presence of these substrings, a message is logged to the console indicating the detected 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

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading