Vanilla JavaScript Browser Detection

— 5 minute read

permalink

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 permalink

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 permalink

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 permalink

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

Thank you for reading, and let's connect! permalink

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