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

[web_stories_embed url=”https://code-boxx.com/web-stories/detect-browser-with-javascript/” title=”How To Detect Browser With Javascript” poster=”https://code-boxx.com/wp-content/uploads/2021/11/STORY-JS-20230518.webp” width=”360″ height=”600″ align=”center”]

Fullscreen Mode – Click Here

 

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

1-user-agent.html
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

2-bowser.html
<!-- (A) LOAD BOWSER -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/bowser/2.11.0/bundled.js"></script>
<script>
// (B) DETECT BROWSER
// https://github.com/lancedikson/bowser 
// https://www.jsdelivr.com/package/npm/bowser
window.addEventListener("load", () => {
  // (B1) PARSE USER AGENT
  var result = bowser.getParser(navigator.userAgent).getResult();
 
  // (B2) BROWSER INFO
  console.log(result.browser.name);
  console.log(result.browser.version);
  console.log(result.engine);
 
  // (B3) OPERATING SYSTEM
  console.log(result.os.name);
  console.log(result.os.version);
  console.log(result.os.versionName);
 
  // (B4) PLATFORM
  console.log(result.platform.type);
});
</script>

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:

3-vendor.html
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);
});

For you guys who do not know, each browser has its own unique set of experimental technologies. To use the experimental and non-standard CSS properties, we have to attach a prefix to the property accordingly:

  • 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

Credits to this post on StackOverflow.

4-duck.html
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.

 

SORRY FOR THE ADS...

But someone has to pay the bills, and sponsors are paying for it. I insist on not turning Code Boxx into a "paid scripts" business, and I don't "block people with Adblock". Every little bit of support helps.

Buy Me A Coffee Code Boxx eBooks

 

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.

 

EXTRA BITS & LINKS

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:

<script src="modernizr-custom.js"></script>
<script>
if (Modernizr.geolocation) {
  // PROCEED 
} else {
  // LOAD POLYFILL OR WARN USER 
}
</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.

 

LINKS & REFERENCES

 

TUTORIAL VIDEO

 

INFOGRAPHIC CHEAT SHEET

How To Detect Browser (Click to Enlarge)

 

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!

6 thoughts on “4 Ways to Detect Browser With Javascript (Simple Examples)”

  1. Jeez… HOW MANY adverts are you going to litter this page with ?!
    Anyway, in 2021, there’s no point using “navigator.userAgent”, they all pretend to be all kinds of browsers.
    And for option 3, nope, Microsoft Edge proudly says it’s “webkit”, which your code thinks is “Chrome/Safari or Opera”
    As for option 4, your code reckons Microsoft Edge was “blink”, and Chrome just didn’t run this code at all.
    Time to give up, me thinks…

    1. Hi! It seems like this is your first time on the Internet. This human worked hard for years to write hundreds of guides, and ads are keeping it free for everyone. Feel free to f*** off and buy books if this arrangement does not work for you.

      Anyway, Edge has become “webkit” ever since it adopted Chromium. User Agent can be changed or removed by the user. Will update this guide eventually, but stick with feature detection if possible.

    2. I rarely post in public forums like this, but just wanted to say: great response to that idiot, Mike. I also rarely advocate for violence, but I wouldn’t mind if someone slapped him across his stupid face. Anyway, keep up the great work, and thank you for sharing all this info. People like you, who selflessly share all this info with the general public, have helped me learn so much through the years.

      I think Modernizr might be the way to go for me.

  2. In your initial test code for using the user agent, shouldn’t the safari check look for the presence of Safari and the absence of Chrome to work well, since you point out that the Chrome header contains the word Safari?

    1. if (navigator.userAgent.indexOf("Safari") != -1 && navigator.userAgent.indexOf("Chrome") == -1) {
        console.log("Safari");
      }

      Yes, that will work too. But I will stick with feature detection unless it’s really for targeting the specific group of users on Safari.

Leave a Comment

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