How to detect the user browser in JavaScript
📅July 4, 2021
Today we will show you how to detect the user browser in JavaScript. There are multiple ways to detect browsers but here we will give you two different methods to do it.
- Sorting an array in JavaScript
- JavaScript switch statement with example
- JavaScript array methods Push, Pop, Shift and Unshift
- JavaScript Spread Operator
- ES6 Rest Parameter in JavaScript
1. Detect user browsers using duck-typing
We have mentioned this method to detect browsers by duck-typing. It’s the most reliable method compared to Method 2.
// Chrome version 1 to 71
var isChromeBrowser = !!window.chrome && (!!window.chrome.webstore || !!window.chrome.runtime);
// Firefox version 1.0+
var isFirefoxBrowser = typeof InstallTrigger !== 'undefined';
// Opera version 8.0+
var isOperaBrowser = (!!window.opr && !!opr.addons) || !!window.opera || navigator.userAgent.indexOf(' OPR/') >= 0;
// Safari version 3.0+ "[object HTMLElementConstructor]"
var isSafariBrowser = /constructor/i.test(window.HTMLElement) || (function (p) { return p.toString() === "[object SafariRemoteNotification]"; })(!window['safari'] || (typeof safari !== 'undefined' && safari.pushNotification));
// Internet Explorer version 6-11
var isIEBrowser = /*@cc_on!@*/false || !!document.documentMode;
// Edge version 20+
var isEdgeBrowser = !isIE && !!window.StyleMedia;
// Edge detection (Based on chromium)
var isEdgeChromium = isChrome && (navigator.userAgent.indexOf("Edg") != -1);
2. Detect user browsers using user agent string
Here we used the navigator.userAgent
string to detect the browser. So we have created a function which will return the name of the browser.
function getBrowser() {
var browser = 'unknown';
var ua = navigator.userAgent;
if ((ua.indexOf("Opera") || ua.indexOf('OPR')) != -1) {
browser = 'Opera'
}
else if (ua.indexOf("Edge") != -1) {
browser = 'Edge'
}
else if (ua.indexOf("Chrome") != -1) {
browser = 'Chrome'
}
else if (ua.indexOf("Safari") != -1) {
browser = 'Safari'
}
else if (ua.indexOf("Firefox") != -1) {
browser = 'Firefox'
}
else if ((ua.indexOf("MSIE") != -1) || (!!document.documentMode == true)) //IF IE > 10
{
browser = 'IE'
}
else {
browser = 'unknown'
}
return browser;
}
I hope you find this article helpful.
Thank you for reading. Happy Coding..!!