Detect Browsers in JavaScript
Today we will show you how to detect browsers in JavaScript. There are multiple ways to detect browsers but here we will give you two different methods to do it.
Detect Browsers in JavaScript, detect browser language version javascript, detect IE Edge Firefox browser in JavaScript, javascript browser detection library, javascript detect browser version, javascript detect browser ie, get browser name and version in javascript, browser detection code, detect browser jquery, javascript user agent detection.
Checkout more articles on JavaScript
- Convert comma separated String into an Array in JavaScript
- Splice and Slice array methods in JavaScript
- Map, Filter and Reduce Operators in JavaScript
- Push, Pop, Shift and Unshift Array Methods in JavaScript
Way to detect browsers in JavaScript
Method 1: Detect browsers by 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);
Method 2: Use user agent string to detect browsers
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;
}
That’s it for today.
Thank you for reading. Happy Coding!