Vanilla JavaScript Browser Detection

โœ๏ธ

Determine which browser a website visitor is using. Detect the browser with this JavaScript code examples.

7 Jul, 2020 ยท 2 min read

Now and then, you might want to show specific alerts based on the web browser a visitor uses.

For instance, this can be because you just made a new Chrome browser extension and want everyone on Chrome to auto-download it.

So let's look in this tutorial how to do browser detection with JavaScript.

Non-Preferred detection method

The non-preferred method of detecting a browser type uses the user-agent. However, a lot of browsers and systems spoof this, so it's not reliable.

We won't be diving into that in this tutorial.

JavaScript Browser Detection

So we'll be using feature detection, it validates browser-specific elements.

What feature detection looks like in code:

// Opera 8.0+
const isOpera =
  (!!window.opr && !!opr.addons) ||
  !!window.opera ||
  navigator.userAgent.indexOf(' OPR/') >= 0;

// Firefox 1.0+
const isFirefox = typeof InstallTrigger !== 'undefined';

// Safari 3.0+ "[object HTMLElementConstructor]"
const isSafari =
  /constructor/i.test(window.HTMLElement) ||
  (function (p) {
    return p.toString() === '[object SafariRemoteNotification]';
  })(
    !window['safari'] ||
      (typeof safari !== 'undefined' && safari.pushNotification)
  );

// Internet Explorer 6-11
const isIE = /*@cc_on!@*/ false || !!document.documentMode;

// Edge 20+
const isEdge = !isIE && !!window.StyleMedia;

// Chrome 1 - 79
const isChrome =
  !!window.chrome && (!!window.chrome.webstore || !!window.chrome.runtime);

// Edge (based on chromium) detection
const isEdgeChromium = isChrome && navigator.userAgent.indexOf('Edg') != -1;

// Blink engine detection
const isBlink = (isChrome || isOpera) && !!window.CSS;

let output = 'Your browser is ๐ŸŽฉ:<br />';
output += 'isFirefox: ' + isFirefox + '<br />';
output += 'isChrome: ' + isChrome + '<br />';
output += 'isSafari: ' + isSafari + '<br />';
output += 'isOpera: ' + isOpera + '<br />';
output += 'isIE: ' + isIE + '<br />';
output += 'isEdge: ' + isEdge + '<br />';
output += 'isEdgeChromium: ' + isEdgeChromium + '<br />';
output += 'isBlink: ' + isBlink + '<br />';
document.body.innerHTML = output;

Credit of this script goes to Rob W

View the example Javascript code for detecting browsers on Codepen

See the Pen Vanilla JavaScript Browser Detection by Chris Bongers (@rebelchris) on CodePen.

Thank you for reading, and let's connect!

Thank you for reading my blog. Feel free to subscribe to my email newsletter and connect on Facebook or Twitter

Spread the knowledge with fellow developers on Twitter
Tweet this tip
Powered by Webmentions - Learn more

Read next ๐Ÿ“–

JavaScript sending data between windows

9 Sep, 2022 ยท 4 min read

JavaScript sending data between windows

Using the native payment request JavaScript API

9 Aug, 2022 ยท 8 min read

Using the native payment request JavaScript API