Check which browser javascript

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.

Читайте также:  Php menu parent id

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 my browser version and operating system using JavaScript?

I have tried using the code below but it only display results in Chrome and Mozilla not working in IE6.

   
Browser CodeName: Mozilla Browser Name: Netscape Browser Version: 5.0 (Windows) Cookies Enabled: true Platform: Win32 User-agent header: Mozilla/5.0 (Windows NT 5.1; rv:12.0) Gecko/20100101 Firefox/12.0 

13 Answers 13

Detecting browser’s details:

var nVer = navigator.appVersion; var nAgt = navigator.userAgent; var browserName = navigator.appName; var fullVersion = ''+parseFloat(navigator.appVersion); var majorVersion = parseInt(navigator.appVersion,10); var nameOffset,verOffset,ix; // In Opera, the true version is after "OPR" or after "Version" if ((verOffset=nAgt.indexOf("OPR"))!=-1) < browserName = "Opera"; fullVersion = nAgt.substring(verOffset+4); if ((verOffset=nAgt.indexOf("Version"))!=-1) fullVersion = nAgt.substring(verOffset+8); >// In MS Edge, the true version is after "Edg" in userAgent else if ((verOffset=nAgt.indexOf("Edg"))!=-1) < browserName = "Microsoft Edge"; fullVersion = nAgt.substring(verOffset+4); >// In MSIE, the true version is after "MSIE" in userAgent else if ((verOffset=nAgt.indexOf("MSIE"))!=-1) < browserName = "Microsoft Internet Explorer"; fullVersion = nAgt.substring(verOffset+5); >// In Chrome, the true version is after "Chrome" else if ((verOffset=nAgt.indexOf("Chrome"))!=-1) < browserName = "Chrome"; fullVersion = nAgt.substring(verOffset+7); >// In Safari, the true version is after "Safari" or after "Version" else if ((verOffset=nAgt.indexOf("Safari"))!=-1) < browserName = "Safari"; fullVersion = nAgt.substring(verOffset+7); if ((verOffset=nAgt.indexOf("Version"))!=-1) fullVersion = nAgt.substring(verOffset+8); >// In Firefox, the true version is after "Firefox" else if ((verOffset=nAgt.indexOf("Firefox"))!=-1) < browserName = "Firefox"; fullVersion = nAgt.substring(verOffset+8); >// In most other browsers, "name/version" is at the end of userAgent else if ( (nameOffset=nAgt.lastIndexOf(' ')+1) < (verOffset=nAgt.lastIndexOf('/')) ) < browserName = nAgt.substring(nameOffset,verOffset); fullVersion = nAgt.substring(verOffset+1); if (browserName.toLowerCase()==browserName.toUpperCase()) < browserName = navigator.appName; >> // trim the fullVersion string at semicolon/space if present if ((ix=fullVersion.indexOf(";"))!=-1) fullVersion=fullVersion.substring(0,ix); if ((ix=fullVersion.indexOf(" "))!=-1) fullVersion=fullVersion.substring(0,ix); majorVersion = parseInt(''+fullVersion,10); if (isNaN(majorVersion)) < fullVersion = ''+parseFloat(navigator.appVersion); majorVersion = parseInt(navigator.appVersion,10); >document.write('' +'Browser name = '+browserName+'
' +'Full version = '+fullVersion+'
' +'Major version = '+majorVersion+'
' +'navigator.appName = '+navigator.appName+'
' +'navigator.userAgent = '+navigator.userAgent+'
' )
// This script sets OSName variable as follows: // "Windows" for all versions of Windows // "MacOS" for all versions of Macintosh OS // "Linux" for all versions of Linux // "UNIX" for all other UNIX flavors // "Unknown OS" indicates failure to detect the OS var OSName="Unknown OS"; if (navigator.appVersion.indexOf("Win")!=-1) OSName="Windows"; if (navigator.appVersion.indexOf("Mac")!=-1) OSName="MacOS"; if (navigator.appVersion.indexOf("X11")!=-1) OSName="UNIX"; if (navigator.appVersion.indexOf("Linux")!=-1) OSName="Linux"; document.write('Your OS: '+OSName);

Источник

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