Javascript test which browser

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 > 

Источник

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!

Источник

Detect Browser using JavaScript

This script will only give you the information about the name of the browser either your website is opened in mobile or desktop browser. So that you can easily calculate the number of different types of browsers that are used to open your website.

javascript detect browser

Javascript Detect Browser

Now, Let’s start to detect different kinds of browsers like chrome, safari, Mozilla Firebox & Microsoft Edge using javascript from the next step.

Learn also –

Create HTML div to display Browser Name

First of all, You have to Create an HTML div to display the browser name after detecting it using javascript. So, You can use the following HTML code within the tag.

I have created the above code that contains a paragraph tag and a bold tag has So that the browser name can be displayed within the bold tag by accessing its id.

Detect Web Browser using JavaScript

Now, Just use this javascript code in your website to detect web browsers. But before using it, you should know its some important points –

I have created a custom function detectBrowser() that is called within the load event to execute it just loading the web page. Also, you can call this function according to your project requirement.

detectBrowser() – This function returns the name of the current web browser that is used to open an website.

  

Test it Yourself on different Browser

After Implementing the previous steps, you can test the JavaScript Browser Detector script by opening in the different kinds of web browsers like Chrome, Mozilla Firefox, Opera, Safari & Edge etc.

Источник

Читайте также:  Yandex market language python
Оцените статью