11

How to detect browser in JavaScript - Codepedia

 3 years ago
source link: https://codepedia.info/detect-browser-in-javascript
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

JavaScript detect browser name: Here in this article we learn how to detect browser in javascript. I had a requirement where based on browser I have to display something different. In short, I have to detect firefox browser in javascript and display the respective message to the user. Same if the user browser is chrome, then display respective message. 

Here we are detecting 5 major browsers and that is Chrome, Firefox, Safari, Opera, MS edge.

Steps to detect browser name in Javascript

  1. HTML markup to display browser name.
  2. JavaScript code to detect browser.

HTML markup to display browser name

First, we create a new index.html page and add the below markup. Here we add an h1 tag, which will display the browser name on page-load.

<html>
   <head>
      <title>Detect Browser in JavaScript</title>
   </head>
   <body>
      	  <h1></h1>	 
   </body>
</html>

Also read: How to Export HTML table to Excel in JavaScript

JavaScript code to detect browser name.

To detect user browser information we use the navigator.userAgent property. And then we match with the browser name to identify the user browser. JS code to identify browser is as written below:

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";
           }
         
          document.querySelector("h1").innerText="You are using "+ browserName +" browser";         
  }

Now call this JS function on page load, and this will display the user browser name on page load.

View Demo

Conclusion: Hereby using navigator.userAgent we were successfully able to detect browser in Javascript. Add display the browser name on page load. It's in pure javascript, as we didn't use any external JS library for the browser detection.   

Recommend

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK