Vanilla JavaScript Browser Detection

— 4 minute read

permalink

Now and then, you might want to show specific alerts based on the browser the 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.

Non Preferred method permalink

The nonpreferred method uses the user-agent, 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 is looks like in code:

// 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+ "[object HTMLElementConstructor]"
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 - 79
var isChrome = !!window.chrome && (!!window.chrome.webstore || !!window.chrome.runtime);

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

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

var 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 this on Codepen.

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