Detect Browser in JavaScript

How to detect browser in JavaScript [Chrome, Firefox, Safari, Opera, Edge , MS IE]?

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. Basically we write code in JavaScript to check user browser. Which help answer to our question .i.e How do I know if I am using IE or Chrome in JavaScript? Here we are detecting 5 major browsers and that are Chrome, Firefox, Safari, Opera, MS Edge. And we are showing 2 different approach to detect browser at client-side i.e using userAgent.match and userAgent.indexOf with live demo example. Although based on different browser display different content is not good practise.

Читайте также:  Java обработка исключений пример

Steps to detect browser name in JavaScript

  1. HTML markup to display browser name.
  2. JavaScript code to detect browser using useragent.match
  3. JavaScript code to detect browser using useragent. indexOf

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.

    

Approach 1: JavaScript code to detect browser name using userAgent.match

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.

Approach 2: JavaScript code to detect browser using userAgent.IndexOf

Here in the 2nd approach we again 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"; 

With the above code will be able to detect chrome browser, also with approach 2, we are able to detect MS Edge browser chromium based. By checking trident we were able to detect MS Internet Explorer browser IE in javascript.

Conclusion: Hereby using the navigator.userAgent we were successfully able to detect Chrome, Firefox, Edge, Safari, and Opera 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.

Thank you for reading, pls keep visiting this blog and share this in your network. Also, I would love to hear your opinions down in the comments.

PS: If you found this content valuable and want to thank me? 👳 Buy Me a Coffee

Subscribe to our newsletter

Get the latest and greatest from Codepedia delivered straight to your inbox.

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

Источник

4 Ways to Detect Browser With Javascript (Simple Examples)

Welcome to a tutorial on how to detect the browser with Javascript. Have some scripts that you only want to run on a certain browser? Maybe limit some features, do some compatibility checks?

The common methods used to detect the browser in Javascript are:

  1. Extract information from the user agent, check if it contains the browser’s name. For example, to check for Chrome browsers – if (navigator.userAgent.indexOf("Chrome") != -1)
  2. Use a detection library such as Bowser.
  3. Detect the CSS vendor prefix – Check if the browser supports WebKit , Moz , or MS .
  4. Browser duck typing – Check for unique features that each browser has.

Yep, there are actually no fixed reliable ways to detect a browser. So just how does each method work, and which is the best? Read on to find out!

TLDR – QUICK SLIDES

How To Detect Browser With Javascript

TABLE OF CONTENTS

BROWSER DETECTION

All right, let us now get started with the ways to detect the browser in Javascript.

METHOD 1) READING THE USER AGENT

window.addEventListener("load", () => < // CHROME if (navigator.userAgent.indexOf("Chrome") != -1 ) < console.log("Google Chrome"); >// FIREFOX else if (navigator.userAgent.indexOf("Firefox") != -1 ) < console.log("Mozilla Firefox"); >// INTERNET EXPLORER else if (navigator.userAgent.indexOf("MSIE") != -1 ) < console.log("Internet Exploder"); >// EDGE else if (navigator.userAgent.indexOf("Edge") != -1 ) < console.log("Internet Exploder"); >// SAFARI else if (navigator.userAgent.indexOf("Safari") != -1 ) < console.log("Safari"); >// OPERA else if (navigator.userAgent.indexOf("Opera") != -1 ) < console.log("Opera"); >// YANDEX BROWSER else if (navigator.userAgent.indexOf("YaBrowser") != -1 ) < console.log("YaBrowser"); >// OTHERS else < console.log("Others"); >>);

The user agent is a piece of information that the browser sends to the server. If you are wondering how it looks like, here is an example from Google Chrome:

Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.110 Safari/537.36

So yes, it contains general information like the browser, operating system, and other software technologies. We can use this for browser detection, and it is as simple as checking if the browser name is stuck somewhere inside the block of text. But take note – Users can choose to hide the user agent, and it is not a totally reliable method.

METHOD 2) USING A DETECTION LIBRARY

   

There are a lot of detection libraries, but the one we are using is called Bowser. As you can see, this one actually relies on the user agent again. It simply parses the information to make things more convenient, but it has the same old problem – Not totally reliable.

METHOD 3) CSS PREFIX DETECTION

Credits to David Walsh for this snippet on how to detect the vendor prefix:

window.addEventListener("load", () => < var prefix = (Array.prototype.slice .call(window.getComputedStyle(document.documentElement, "")) .join("") .match(/-(moz|webkit|ms)-/))[1]; // MOZ - FIREFOX (GECKO ENGINE) // WEBKIT - CHROME, SAFARI, OPERA, EDGE (WEBKIT ENGINE) // MS - OLD INTERNET EXPLORER & EDGE (TRIDENT ENGINE) // NOTE - OLD OPERA VERSIONS USE PRESTO ENGINE. PREFIX IS -O console.log(prefix); >);
  • WebKit – For Chrome, Safari, Opera, and Edge.
  • Moz – Mozilla Firefox.
  • MS – Old Microsoft Internet Explorer and Edge.
  • O – Older versions of Opera.

So yes, we can detect which CSS prefix the browser uses, and determine which engine the browser runs on. While this is more reliable in the sense that users cannot turn it off, there is also no way to tell which browser it is exactly.

P.S. In Jan 2020, Edge has become Chromium-based. The older versions retain MS but later versions are WebKit .

METHOD 4) DUCK TYPING

window.addEventListener("load", () => < // OPERA 8.0+ var isOpera = (!!window.opr && !!opr.addons) || !!window.opera || navigator.userAgent.indexOf(' OPR/') >= 0; // FIREFOX 1.0+ var isFirefox = typeof InstallTrigger !== 'undefined'; // SAFARI 3.0+ var isSafari = /constructor/i.test(window.HTMLElement) || (function (p) < return p.toString() === "[object SafariRemoteNotification]"; >)(!window['safari'] || (typeof safari !== 'undefined' && safari.pushNotification)); // INTERNET EXPLORER 6-11 var isIE = /*@cc_on!@*/false || !!document.documentMode; // EDGE 20+ var isEdge = !isIE && !!window.StyleMedia; // CHROME 1+ var isChrome = !!window.chrome; // BLINK ENGINE DETECTION var isBlink = (isChrome || isOpera) && !!window.CSS; console.log("Opera - " + isOpera); console.log("Firefox - " + isFirefox); console.log("Safari - " + isSafari); console.log("IE - " + isIE); console.log("Edge - " + isEdge); console.log("Chrome - " + isChrome); console.log("Blink - " + isBlink); >);

Duck typing is simply detecting the “odd quirks” and “unique features” of each browser. For example, window.opr and window.opera is unique to Opera, and window.chrome is unique to Chrome. While this is probably one of the most reliable methods, it takes a lot of time to figure out what is unique to each browser – A real pain to keep this list updated.

DOWNLOAD & NOTES

Here is the download link to the example code, so you don’t have to copy-paste everything.

SUPPORT

600+ free tutorials & projects on Code Boxx and still growing. I insist on not turning Code Boxx into a "paid scripts and courses" business, so every little bit of support helps.

EXAMPLE CODE DOWNLOAD

Click here for the source code on GitHub gist, just click on “download zip” or do a git clone. I have released it under the MIT license, so feel free to build on top of it or use it in your own project.

That’s all for this tutorial, and here is a small section on some extras and links that may be useful to you.

USER AGENT IS NOT ACCURATE!

Please take note that the user agent can be easily tweaked with development tools and plugins. Yes, it is not 100% accurate, users can hide it for security purposes, or even change it to something else for testing.

WHICH IS THE BEST? FEATURE DETECTION.

Personally, I will say that none of the above detection methods are reliable. If you are trying to do backward or cross-platform compatibility, then browser detection doesn’t make any sense. Do feature detection instead. I personally use a library called Modernizr, and for example, if we need to check the user’s physical location via GPS, we check for support for the Geolocation API.

Download your customized Modernizr build, then just include in your script:

  

I hope this makes more sense, we just check if the required feature is available; It is very inefficient to try to figure out which browser, which version is capable, and which is not.

TUTORIAL VIDEO

INFOGRAPHIC CHEAT SHEET

THE END

Thank you for reading, and we have come to the end of this guide. I hope that it has helped you with your project, and if you want to share anything with this guide, please feel free to comment below. Good luck and happy coding!

Источник

How to detect the user browser with JavaScript

Learn how to detect which browser the user is running (Chrome, IE, LightHouse, FireFox, Safari, etc.) using plain JavaScript.

You can check which browser the user is running using plain JavaScript.

To detect the user browser, you need to analyze the property userAgent of the object navigator .

If you want to do something specific, for example, provide a polifill for a regular expression when the browser is Safari, you do this:

if (navigator.userAgent.includes('Safari')) < // the user is running Safari // do something useful > 

On the other hand, if you want to do something for all browsers but Chrome , you check if the userAgent doesn’t include your search string:

if (!navigator.userAgent.includes('Chrome')) < // the user is NOT running Chrome > 

Using indexOf and toLowerCase

As an alternative to includes you can also use the indexOf method. If it returns -1 , this means that the search string wasn’t found.

if (navigator.userAgent.indexOf('Chrome')  0) < // the user is NOT running Chrome > 

If you’re not sure how exactly the user browser is spelled, you can try using the toLowerCase function on the navigator.userAgent .

if (navigator.userAgent.toLowerCase().indexOf('chrome')  0) < // the user is NOT running Chrome > 

Источник

Оцените статью