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 at this tutorial on browser detection with JavaScript.
Non-Preferred detection method
The non-preferred method of detecting a browser type uses the user agent. However, many browsers and systems spoof this, so it’s unreliable.
We won’t be diving into that in this tutorial.
JavaScript Browser Detection
So we’ll be using feature detection, which 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 for 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