Javascript Detecting IE11 Version [duplicate] - javascript

This question already has answers here:
Internet Explorer 11 detection
(12 answers)
Closed 7 years ago.
I'm working on correctly finding client browser version in the code below. Everything works but IE11 version number. I keep getting a value of 5. The browser shows correctly for all version that I tested but IE11. I've tried a few things but I'm stumped. Can anyone help me with what I'm missing, Thank you.
// BrowserInformation
vm.objappVersion = navigator.appVersion;
vm.objAgent = navigator.userAgent;
vm.objbrowserName = navigator.appName;
vm.objfullVersion = ''+parseFloat(navigator.appVersion);
vm.objBrMajorVersion = parseInt(navigator.appVersion,10);
vm.objOffsetName = '';
vm.objOffsetVersion = '';
vm.ix;
// In Chrome
if ((vm.objOffsetVersion = vm.objAgent.indexOf("Chrome")) != -1) {
vm.objbrowserName = "Chrome"; vm.objfullVersion = vm.objAgent.substring(vm.objOffsetVersion + 7);
}
// In IE11
else if ((vm.objOffsetVersion = vm.objAgent.indexOf("rv")) != -1) {
vm.objbrowserName = "Microsoft Internet Explorer Version 11"; vm.objfullVersion = vm.objAgent.substring(vm.objOffsetVersion + 10);
}
// In Microsoft internet explorer all other versions
else if ((vm.objOffsetVersion = vm.objAgent.indexOf("MSIE")) != -1) {
vm.objbrowserName = "Microsoft Internet Explorer"; vm.objfullVersion = vm.objAgent.substring(vm.objOffsetVersion + 5);
}
// In Firefox
else if ((vm.objOffsetVersion = vm.objAgent.indexOf("Firefox")) != -1) {
vm.objbrowserName = "Firefox";
}
// In Safari
else if ((vm.objOffsetVersion = vm.objAgent.indexOf("Safari")) != -1) {
vm.objbrowserName = "Safari"; vm.objfullVersion = vm.objAgent.substring(vm.objOffsetVersion + 7);
if ((vm.objOffsetVersion = vm.objAgent.indexOf("Version")) != -1) vm.objfullVersion = vm.objAgent.substring(vm.objOffsetVersion + 8);
}
// For other browser "name/version" is at the end of userAgent
else if ((vm.objOffsetName = vm.objAgent.lastIndexOf(' ') + 1) < (vm.objOffsetVersion = vm.objAgent.lastIndexOf('/'))) {
vm.objbrowserName = vm.objAgent.substring(vm.objOffsetName, vm.objOffsetVersion); vm.objfullVersion = vm.objAgent.substring(vm.objOffsetVersion + 1);
if (vm.objbrowserName.toLowerCase() == vm.objbrowserName.toUpperCase()) { vm.objbrowserName = navigator.appName; }
}
// trimming the fullVersion string at semicolon/space if present
if ((vm.ix = vm.objfullVersion.indexOf(";")) != -1)
vm.objfullVersion = vm.objfullVersion.substring(0, vm.ix);
if ((vm.ix = vm.objfullVersion.indexOf(" ")) != -1)
vm.objfullVersion = vm.objfullVersion.substring(0, vm.ix);
vm.objBrMajorVersion = parseInt('' + vm.objfullVersion, 10);
if (isNaN(vm.objBrMajorVersion)) {
vm.objfullVersion = '' + parseFloat(navigator.appVersion);
vm.objBrMajorVersion = parseInt(navigator.appVersion, 10);
}

Here is an update of your script that works
vm.objappVersion = navigator.appVersion;
vm.objAgent = navigator.userAgent;
vm.objbrowserName = navigator.appName;
vm.objfullVersion = ''+parseFloat(navigator.appVersion);
vm.objBrMajorVersion = parseInt(navigator.appVersion,10);
vm.objOffsetName = '';
vm.objOffsetVersion = '';
vm.ix;
// In Chrome
if ((vm.objOffsetVersion = vm.objAgent.indexOf("Chrome")) != -1) {
vm.objbrowserName = "Chrome"; vm.objfullVersion = vm.objAgent.substring(vm.objOffsetVersion + 7);
}
// In IE11
else if ((vm.objOffsetVersion = vm.objAgent.indexOf("rv")) != -1) {
vm.objbrowserName = "Microsoft Internet Explorer Version 11"; vm.objfullVersion = vm.objAgent.substring(vm.objOffsetVersion + 2);
}
// In Microsoft internet explorer all other versions
else if ((vm.objOffsetVersion = vm.objAgent.indexOf("MSIE")) != -1) {
vm.objbrowserName = "Microsoft Internet Explorer"; vm.objfullVersion = vm.objAgent.substring(vm.objOffsetVersion + 5);
}
// In Firefox
else if ((vm.objOffsetVersion = vm.objAgent.indexOf("Firefox")) != -1) {
vm.objbrowserName = "Firefox";
}
// In Safari
else if ((vm.objOffsetVersion = vm.objAgent.indexOf("Safari")) != -1) {
vm.objbrowserName = "Safari"; vm.objfullVersion = vm.objAgent.substring(vm.objOffsetVersion + 7);
if ((vm.objOffsetVersion = vm.objAgent.indexOf("Version")) != -1) vm.objfullVersion = vm.objAgent.substring(vm.objOffsetVersion + 8);
}
// For other browser "name/version" is at the end of userAgent
else if ((vm.objOffsetName = vm.objAgent.lastIndexOf(' ') + 1) < (vm.objOffsetVersion = vm.objAgent.lastIndexOf('/'))) {
vm.objbrowserName = vm.objAgent.substring(vm.objOffsetName, vm.objOffsetVersion); vm.objfullVersion = vm.objAgent.substring(vm.objOffsetVersion + 1);
if (vm.objbrowserName.toLowerCase() == vm.objbrowserName.toUpperCase()) { vm.objbrowserName = navigator.appName; }
}
// trimming the fullVersion string at semicolon/space if present
if ((vm.ix = vm.objfullVersion.indexOf(";")) != -1) {
vm.objfullVersion = vm.objfullVersion.substring(0, vm.ix);
}
if ((vm.ix = vm.objfullVersion.indexOf(":")) != -1) {
vm.ix = vm.objfullVersion.indexOf(")");
vm.objfullVersion = vm.objfullVersion.substring(1, vm.ix);
vm.objBrMajorVersion = parseInt('' + vm.objfullVersion, 10);
}
if ((vm.ix = vm.objfullVersion.indexOf(" ")) != -1) {
vm.objfullVersion = vm.objfullVersion.substring(0, vm.ix);
vm.objBrMajorVersion = parseInt('' + vm.objfullVersion, 10);
}
if (isNaN(vm.objBrMajorVersion)) {
vm.objfullVersion = '' + parseFloat(navigator.appVersion);
vm.objBrMajorVersion = parseInt(navigator.appVersion, 10);
}
Changed the following line:
vm.objbrowserName = "Microsoft Internet Explorer Version 11"; vm.objfullVersion = vm.objAgent.substring(vm.objOffsetVersion + 2);
And added these lines
if ((vm.ix = vm.objfullVersion.indexOf(":")) != -1) {
vm.ix = vm.objfullVersion.indexOf(")");
vm.objfullVersion = vm.objfullVersion.substring(1, vm.ix);
vm.objBrMajorVersion = parseInt('' + vm.objfullVersion, 10);
}
Side note:
I do recommend though, to be careful sniffing/detecting like that, as it can easily go wrong.

Related

How to know name of browser javascript?

How to know name of browser javascript , I want to know if browser is IE or not,
I tried to use this
navigator.appName
but this code it give the same result with
IE11, Firefox, Chrome and Safari returns "Netscape"
How can i know IE ? ( I don,t care for versions )
Here are all the information that you need (but is not the first time that a similar question was done here):
var nVer = navigator.appVersion;
var nAgt = navigator.userAgent;
var browserName = navigator.appName;
var fullVersion = ''+parseFloat(navigator.appVersion);
var majorVersion = parseInt(navigator.appVersion,10);
var nameOffset,verOffset,ix;
// In Opera, the true version is after "Opera" or after "Version"
if ((verOffset=nAgt.indexOf("Opera"))!=-1) {
browserName = "Opera";
fullVersion = nAgt.substring(verOffset+6);
if ((verOffset=nAgt.indexOf("Version"))!=-1)
fullVersion = nAgt.substring(verOffset+8);
}
// In MSIE, the true version is after "MSIE" in userAgent
else if ((verOffset=nAgt.indexOf("MSIE"))!=-1) {
browserName = "Microsoft Internet Explorer";
fullVersion = nAgt.substring(verOffset+5);
}
// In Chrome, the true version is after "Chrome"
else if ((verOffset=nAgt.indexOf("Chrome"))!=-1) {
browserName = "Chrome";
fullVersion = nAgt.substring(verOffset+7);
}
// In Safari, the true version is after "Safari" or after "Version"
else if ((verOffset=nAgt.indexOf("Safari"))!=-1) {
browserName = "Safari";
fullVersion = nAgt.substring(verOffset+7);
if ((verOffset=nAgt.indexOf("Version"))!=-1)
fullVersion = nAgt.substring(verOffset+8);
}
// In Firefox, the true version is after "Firefox"
else if ((verOffset=nAgt.indexOf("Firefox"))!=-1) {
browserName = "Firefox";
fullVersion = nAgt.substring(verOffset+8);
}
// In most other browsers, "name/version" is at the end of userAgent
else if ( (nameOffset=nAgt.lastIndexOf(' ')+1) < (verOffset=nAgt.lastIndexOf('/')) ) {
browserName = nAgt.substring(nameOffset,verOffset);
fullVersion = nAgt.substring(verOffset+1);
if (browserName.toLowerCase()==browserName.toUpperCase()) {
browserName = navigator.appName;
}
}
// trim the fullVersion string at semicolon/space if present
if ((ix=fullVersion.indexOf(";"))!=-1)
fullVersion=fullVersion.substring(0,ix);
if ((ix=fullVersion.indexOf(" "))!=-1)
fullVersion=fullVersion.substring(0,ix);
majorVersion = parseInt(''+fullVersion,10);
if (isNaN(majorVersion)) {
fullVersion = ''+parseFloat(navigator.appVersion);
majorVersion = parseInt(navigator.appVersion,10);
}
document.write(''
+'Browser name = '+browserName+'<br>'
+'Full version = '+fullVersion+'<br>'
+'Major version = '+majorVersion+'<br>'
+'navigator.appName = '+navigator.appName+'<br>'
+'navigator.userAgent = '+navigator.userAgent+'<br>');
var IE = (function msieversion() {
var ua = window.navigator.userAgent;
var msie = ua.indexOf("MSIE ");
if (msie > 0 || !!navigator.userAgent.match(/Trident.*rv\:11\./)) // If Internet Explorer, return version number
return true;
else // If another browser, return 0
return false;
return false;
})();
var SAFARI = navigator.userAgent.indexOf('Safari') > -1 && navigator.userAgent.indexOf('Windows') > -1 && navigator.userAgent.indexOf('Chrome') == -1; // Safari for Windows
var ANDROID = navigator.userAgent.toLowerCase().indexOf("android") > -1;
var IOS = ( function() {
var userAgent = navigator.userAgent || navigator.vendor || window.opera;
if( userAgent.match( /iPad/i ) || userAgent.match( /iPhone/i ) || userAgent.match( /iPod/i ) )
{
return true;
}
return false;
})();

Javascript is not working in IE

I am writing a javascript, that ll get the browser information and set them in cookies, so that I can use them in future.
The setCookies() is complext javascript function, that ll do some manipulation on the navoigator user agent and determine the browser.
This functions seems to work on all major browsers, but it is not working in IE (11, 10, 9, 8 , 7), I don't know why.
Other info : I am developing a Apache wicket application, version 1.4.19.
Here is the Javascript function
<script type="text/javascript">
function setCookies() {
var browser;
var version;
var click_ev = document.createEvent("MouseEvents");
click_ev.initEvent("click", true /* bubble */, true /* cancelable */);
document.cookie = "user_agent=" + navigator.userAgent + "; path=/";
document.cookie = "navigator_app_platform=" + navigator.platform
+ "; path=/";
var platform = navigator.platform;
if (platform == "iPad" || platform == "iPhone" || platform == "iPod"
|| platform == "iPod touch") { // For iPhones iPads and iPods
var userAgent = navigator.userAgent;
var chromeIndex = userAgent.indexOf("criOS");
var opera = userAgent.indexOf("OPiOS");
var ucIndex = userAgent.indexOf("UCBrowser");
var coast = userAgent.indexOf("Coast");
var mercury = userAgent.indexOf("Mercury");
var safari = userAgent.indexOf("Safari");
var webkit = userAgent.indexOf("AppleWebKit");
// Chrome detection
if(chromeIndex > 0) {
browser = "chrome";
var arr = userAgent.split("criOS/");
arr = arr[1].split(".");
version = arr[0];
}
// Safari detection
else if(opera < 0 && ucIndex < 0 && coast < 0 && mercury < 0 && safari > 0 && webkit > 0) {
browser = "safari";
var arr = userAgent.split("AppleWebKit/");
arr = arr[1].split(".");
version = arr[0];
} else {
browser = "unknown";
version = -1;
}
} else if(platform == "Win32" || platform == "MacIntel") { // For windows and mac
// Browser detection
var isOpera = !!window.opera || navigator.userAgent.indexOf(' OPR/') >= 0;
// Opera 8.0+ (UA detection to detect Blink/v8-powered Opera)
var isFirefox = typeof InstallTrigger !== 'undefined'; // Firefox 1.0+
var isSafari = Object.prototype.toString.call(window.HTMLElement).indexOf('Constructor') > 0;
// At least Safari 3+: "[object HTMLElementConstructor]"
var isChrome = !!window.chrome && !isOpera; // Chrome 1+
var isIE = /*#cc_on!#*/false || !!document.documentMode; // At least IE6
if (isOpera) {
browser = "opera";
} else if (isFirefox) {
browser = "firefox";
} else if (isChrome) {
browser = "chrome";
} else if (isIE) {
browser = "ie";
} else if (isSafari) {
browser = "safari";
} else {
browser = "unknown";
}
if (browser == "firefox") {
var arr = navigator.userAgent.split("Firefox/");
arr = arr[1].split(".");
version = arr[0];
} else if (browser == "chrome") {
var arr = navigator.userAgent.split("Chrome/");
arr = arr[1].split(".");
version = arr[0];
} else if (browser == "ie") {
var arr = navigator.userAgent.split("MSIE ");
arr = arr[1].split(".");
version = arr[0];
} else if (browser == "safari") {
var arr = navigator.userAgent.split("AppleWebKit/");
arr = arr[1].split(" ");
arr = arr[0].split(".");
version = arr[0];
} else if (browser == "opera") {
var arr = navigator.userAgent.split("OPR/");
arr = arr[1].split(".");
version = arr[0];
} else if (browser == "unknown") {
version = -1;
}
} else if(platform == "Android" || platform == "Linux armv7l") { // For android
var userAgent = navigator.userAgent;
var chromeIndex = userAgent.indexOf("Chrome");
var opera = userAgent.indexOf("OPR");
var ucIndex = userAgent.indexOf("UCBrowser");
var coast = userAgent.indexOf("Coast");
var firefox = userAgent.indexOf("Firefox");
// Chrome detection
if(chromeIndex > 0 && opera < 0 && ucIndex < 0 && coast < 0) {
browser = "chrome";
var arr = userAgent.split("Chrome/");
arr = arr[1].split(".");
version = arr[0];
} else if(firefox > 0) { // Firefox detection
browser = "firefox";
var arr = userAgent.split("Firefox/");
arr = arr[1].split(".");
version = arr[0];
} else if(opera > 0) { // Opera detection
browser = "opera";
var arr = userAgent.split("OPR/");
arr = arr[1].split(".");
version = arr[0];
} else { // Unknown browser
browser = "unknown";
version = -1;
}
} else { // For other platforms
version = -1;
browser = "other_platform";
}
document.cookie = "browser_version=" + version + "; path=/";
document.cookie = "browser_name=" + browser + "; path=/";
document.getElementById("redirect").dispatchEvent(click_ev);
}
</script>
I did fix the issue after some playing around.
It turned out that, in the newer versions of IE userAgent is not same in every versions.
The user agent in my IE10 does not contain "MSIE", and I was trying to split the userAgent by "MSIE", and it was resulting a null pointer situation.
So the IE version detection script changed from :
if (browser == "ie") {
var arr = navigator.userAgent.split("MSIE ");
arr = arr[1].split(".");
version = arr[0];
}
To :
if (browser == "ie") {
var v1 = navigator.userAgent.indexOf("MISE");
var v2 = navigator.userAgent.indexOf("rv:");
if(v1 > 0) {
var arr = navigator.userAgent.split("MSIE ");
arr = arr[1].split(".");
version = arr[0];
} else if(v2 > 0) {
var arr = navigator.userAgent.split("rv:");
arr = arr[1].split(".");
version = arr[0];
}
Thanks :)

How to detect Safari, Chrome, IE, Firefox and Opera browsers?

I have 5 addons/extensions for Firefox, Chrome, Internet Explorer(IE), Opera, and Safari.
How can I correctly recognize the user browser and redirect (once an install button has been clicked) to download the corresponding addon?
Googling for browser reliable detection often results in checking the User agent string. This method is not reliable, because it's trivial to spoof this value.
I've written a method to detect browsers by duck-typing.
Only use the browser detection method if it's truly necessary, such as showing browser-specific instructions to install an extension. Use feature detection when possible.
Demo: https://jsfiddle.net/6spj1059/
// 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' && window['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 = 'Detecting browsers by ducktyping:<hr>';
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;
Analysis of reliability
The previous method depended on properties of the rendering engine (-moz-box-sizing and -webkit-transform) to detect the browser. These prefixes will eventually be dropped, so to make detection even more robust, I switched to browser-specific characteristics:
Internet Explorer: JScript's Conditional compilation (up until IE9) and document.documentMode.
Edge: In Trident and Edge browsers, Microsoft's implementation exposes the StyleMedia constructor. Excluding Trident leaves us with Edge.
Edge (based on chromium): The user agent include the value "Edg/[version]" at the end (ex: "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.16 Safari/537.36 Edg/80.0.361.9").
Firefox: Firefox's API to install add-ons: InstallTrigger
Chrome: The global chrome object, containing several properties including a documented chrome.webstore object.
Update 3 chrome.webstore is deprecated and undefined in recent versions
Safari: A unique naming pattern in its naming of constructors. This is the least durable method of all listed properties and guess what? In Safari 9.1.3 it was fixed. So we are checking against SafariRemoteNotification, which was introduced after version 7.1, to cover all Safaris from 3.0 and upwards.
Opera: window.opera has existed for years, but will be dropped when Opera replaces its engine with Blink + V8 (used by Chromium).
Update 1: Opera 15 has been released, its UA string looks like Chrome, but with the addition of "OPR". In this version the chrome object is defined (but chrome.webstore isn't). Since Opera tries hard to clone Chrome, I use user agent sniffing for this purpose.
Update 2: !!window.opr && opr.addons can be used to detect Opera 20+ (evergreen).
Blink: CSS.supports() was introduced in Blink once Google switched on Chrome 28. It's of course, the same Blink used in Opera.
Successfully tested in:
Firefox 0.8 - 61
Chrome 1.0 - 71
Opera 8.0 - 34
Safari 3.0 - 10
IE 6 - 11
Edge - 20-42
Edge Dev - 80.0.361.9
Updated in November 2016 to include detection of Safari browsers from 9.1.3 and upwards
Updated in August 2018 to update the latest successful tests on chrome, firefox IE and edge.
Updated in January 2019 to fix chrome detection (because of the window.chrome.webstore deprecation) and include the latest successful tests on chrome.
Updated in December 2019 to add Edge based on Chromium detection (based on the #Nimesh comment).
You can try following way to check Browser version.
<!DOCTYPE html>
<html>
<body>
<p>What is the name(s) of your browser?</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction() {
if((navigator.userAgent.indexOf("Opera") || navigator.userAgent.indexOf('OPR')) != -1 )
{
alert('Opera');
}
else if(navigator.userAgent.indexOf("Edg") != -1 )
{
alert('Edge');
}
else if(navigator.userAgent.indexOf("Chrome") != -1 )
{
alert('Chrome');
}
else if(navigator.userAgent.indexOf("Safari") != -1)
{
alert('Safari');
}
else if(navigator.userAgent.indexOf("Firefox") != -1 )
{
alert('Firefox');
}
else if((navigator.userAgent.indexOf("MSIE") != -1 ) || (!!document.documentMode == true )) //IF IE > 10
{
alert('IE');
}
else
{
alert('unknown');
}
}
</script>
</body>
</html>
And if you need to know only IE Browser version then you can follow below code. This code works well for version IE6 to IE11
<!DOCTYPE html>
<html>
<body>
<p>Click on Try button to check IE Browser version.</p>
<button onclick="getInternetExplorerVersion()">Try it</button>
<p id="demo"></p>
<script>
function getInternetExplorerVersion() {
var ua = window.navigator.userAgent;
var msie = ua.indexOf("MSIE ");
var rv = -1;
if (msie > 0 || !!navigator.userAgent.match(/Trident.*rv\:11\./)) // If Internet Explorer, return version number
{
if (isNaN(parseInt(ua.substring(msie + 5, ua.indexOf(".", msie))))) {
//For IE 11 >
if (navigator.appName == 'Netscape') {
var ua = navigator.userAgent;
var re = new RegExp("Trident/.*rv:([0-9]{1,}[\.0-9]{0,})");
if (re.exec(ua) != null) {
rv = parseFloat(RegExp.$1);
alert(rv);
}
}
else {
alert('otherbrowser');
}
}
else {
//For < IE11
alert(parseInt(ua.substring(msie + 5, ua.indexOf(".", msie))));
}
return false;
}}
</script>
</body>
</html>
Here are several prominent libraries that handle browser detection as of Dec 2019.
Bowser by lancedikson - 4,065★s - Last updated Oct 2, 2019 - 4.8KB
var result = bowser.getParser(window.navigator.userAgent);
console.log(result);
document.write("You are using " + result.parsedResult.browser.name +
" v" + result.parsedResult.browser.version +
" on " + result.parsedResult.os.name);
<script src="https://unpkg.com/bowser#2.7.0/es5.js"></script>
*supports Edge based on Chromium
Platform.js by bestiejs - 2,550★s - Last updated Apr 14, 2019 - 5.9KB
console.log(platform);
document.write("You are using " + platform.name +
" v" + platform.version +
" on " + platform.os);
<script src="https://cdnjs.cloudflare.com/ajax/libs/platform/1.3.5/platform.min.js"></script>
jQuery Browser by gabceb - 504★s - Last updated Nov 23, 2015 - 1.3KB
console.log($.browser)
document.write("You are using " + $.browser.name +
" v" + $.browser.versionNumber +
" on " + $.browser.platform);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-browser/0.1.0/jquery.browser.min.js"></script>
Detect.js (Archived) by darcyclarke - 522★s - Last updated Oct 26, 2015 - 2.9KB
var result = detect.parse(navigator.userAgent);
console.log(result);
document.write("You are using " + result.browser.family +
" v" + result.browser.version +
" on " + result.os.family);
<script src="https://cdnjs.cloudflare.com/ajax/libs/Detect.js/2.2.2/detect.min.js"></script>
Browser Detect (Archived) by QuirksMode - Last updated Nov 14, 2013 - 884B
console.log(BrowserDetect)
document.write("You are using " + BrowserDetect.browser +
" v" + BrowserDetect.version +
" on " + BrowserDetect.OS);
<script src="https://kylemit.github.io/libraries/libraries/BrowserDetect.js"></script>
Notable Mentions:
WhichBrowser - 1,355★s - Last updated Oct 2, 2018
Modernizr - 23,397★s - Last updated Jan 12, 2019 - To feed a fed horse, feature detection should drive any canIuse style questions. Browser detection is really just for providing customized images, download files, or instructions for individual browsers.
Further Reading
Stack Overflow - Browser detection in JavaScript?
Stack Overflow - How can you detect the version of a browser?
I know it may be overkill to use a lib for that, but just to enrich the thread, you could check is.js way of doing this:
is.firefox();
is.ie(6);
is.not.safari();
In case anyone finds this useful, I've made Rob W's answer into a function that returns the browser string rather than having multiple variables floating about. Since the browser also can't really change without loading all over again, I've made it cache the result to prevent it from needing to work it out the next time the function is called.
/**
* Gets the browser name or returns an empty string if unknown.
* This function also caches the result to provide for any
* future calls this function has.
*
* #returns {string}
*/
var browser = function() {
// Return cached result if avalible, else get result then cache it.
if (browser.prototype._cachedResult)
return browser.prototype._cachedResult;
// 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'] || safari.pushNotification);
// Internet Explorer 6-11
var isIE = /*#cc_on!#*/false || !!document.documentMode;
// Edge 20+
var isEdge = !isIE && !!window.StyleMedia;
// Chrome 1+
var isChrome = !!window.chrome && !!window.chrome.webstore;
// Blink engine detection
var isBlink = (isChrome || isOpera) && !!window.CSS;
return browser.prototype._cachedResult =
isOpera ? 'Opera' :
isFirefox ? 'Firefox' :
isSafari ? 'Safari' :
isChrome ? 'Chrome' :
isIE ? 'IE' :
isEdge ? 'Edge' :
isBlink ? 'Blink' :
"Don't know";
};
console.log(browser());
Short variant (update 10 july 2020 mobile browser detection fix)
var browser = (function() {
var test = function(regexp) {return regexp.test(window.navigator.userAgent)}
switch (true) {
case test(/edg/i): return "Microsoft Edge";
case test(/trident/i): return "Microsoft Internet Explorer";
case test(/firefox|fxios/i): return "Mozilla Firefox";
case test(/opr\//i): return "Opera";
case test(/ucbrowser/i): return "UC Browser";
case test(/samsungbrowser/i): return "Samsung Browser";
case test(/chrome|chromium|crios/i): return "Google Chrome";
case test(/safari/i): return "Apple Safari";
default: return "Other";
}
})();
console.log(browser)
Typescript version:
export enum BROWSER_ENUM {
EDGE ,
INTERNET_EXPLORER ,
FIRE_FOX ,
OPERA ,
UC_BROWSER ,
SAMSUNG_BROWSER ,
CHROME ,
SAFARI ,
UNKNOWN ,
}
const testUserAgent = (regexp: RegExp): boolean => regexp.test(window.navigator.userAgent);
function detectBrowser(): BROWSER_ENUM {
switch (true) {
case testUserAgent(/edg/i): return BROWSER_ENUM.EDGE;
case testUserAgent(/trident/i): return BROWSER_ENUM.INTERNET_EXPLORER;
case testUserAgent(/firefox|fxios/i): return BROWSER_ENUM.FIRE_FOX;
case testUserAgent(/opr\//i): return BROWSER_ENUM.OPERA;
case testUserAgent(/ucbrowser/i): return BROWSER_ENUM.UC_BROWSER;
case testUserAgent(/samsungbrowser/i): return BROWSER_ENUM.SAMSUNG_BROWSER;
case testUserAgent(/chrome|chromium|crios/i): return BROWSER_ENUM.CHROME;
case testUserAgent(/safari/i): return BROWSER_ENUM.SAFARI;
default: return BROWSER_ENUM.UNKNOWN;
}
}
export const BROWSER: BROWSER_ENUM = detectBrowser();
export const IS_FIREFOX = BROWSER === BROWSER_ENUM.FIRE_FOX;
Functional algorithm, just for fun:
var BROWSER = new Array(
["Microsoft Edge", /edg/i],
["Microsoft Internet Explorer", /trident/i],
["Mozilla Firefox", /firefox|fxios/i],
["Opera", /opr\//i],
["UC Browser", /ucbrowser/i],
["Samsung Browser", /samsungbrowser/i],
["Google Chrome", /chrome|chromium|crios/i],
["Apple Safari", /safari/i],
["Unknown", /.+/i],
).find(([, value]) => value.test(window.navigator.userAgent)).shift();
No idea if it is useful to anyone but here is a variant that would make TypeScript happy:
export function getBrowser() {
// Opera 8.0+
if ((!!window["opr"] && !!["opr"]["addons"]) || !!window["opera"] || navigator.userAgent.indexOf(' OPR/') >= 0) {
return 'opera';
}
// Firefox 1.0+
if (typeof window["InstallTrigger"] !== 'undefined') {
return 'firefox';
}
// Safari 3.0+ "[object HTMLElementConstructor]"
if (/constructor/i.test(window["HTMLElement"]) || (function(p) { return p.toString() === "[object SafariRemoteNotification]"; })(!window['safari'] || (typeof window["safari"] !== 'undefined' && window["safari"].pushNotification))) {
return 'safari';
}
// Internet Explorer 6-11
if (/*#cc_on!#*/false || !!document["documentMode"]) {
return 'ie';
}
// Edge 20+
if (!(/*#cc_on!#*/false || !!document["documentMode"]) && !!window["StyleMedia"]) {
return 'edge';
}
// Chrome 1+
if (!!window["chrome"] && !!window["chrome"].webstore) {
return 'chrome';
}
// Blink engine detection
if (((!!window["chrome"] && !!window["chrome"].webstore) || ((!!window["opr"] && !!["opr"]["addons"]) || !!window["opera"] || navigator.userAgent.indexOf(' OPR/') >= 0)) && !!window["CSS"]) {
return 'blink';
}
}
Thank you, everybody. I tested the code snippets here on the recent browsers: Chrome 55, Firefox 50, IE 11 and Edge 38, and I came up with the following combination that worked for me for all of them. I'm sure it can be improved, but it's a quick solution for whoever needs:
var browser_name = '';
isIE = /*#cc_on!#*/false || !!document.documentMode;
isEdge = !isIE && !!window.StyleMedia;
if(navigator.userAgent.indexOf("Chrome") != -1 && !isEdge)
{
browser_name = 'chrome';
}
else if(navigator.userAgent.indexOf("Safari") != -1 && !isEdge)
{
browser_name = 'safari';
}
else if(navigator.userAgent.indexOf("Firefox") != -1 )
{
browser_name = 'firefox';
}
else if((navigator.userAgent.indexOf("MSIE") != -1 ) || (!!document.documentMode == true )) //IF IE > 10
{
browser_name = 'ie';
}
else if(isEdge)
{
browser_name = 'edge';
}
else
{
browser_name = 'other-browser';
}
$('html').addClass(browser_name);
It adds a CSS class to the HTML, with the name of the browser.
Here's a 2016 adjusted version of Rob's answer, including Microsoft Edge and detection of Blink:
(edit: I updated Rob's answer above with this information.)
// Opera 8.0+ (UA detection to detect Blink/v8-powered Opera)
isOpera = !!window.opera || navigator.userAgent.indexOf(' OPR/') >= 0;
// Firefox 1.0+
isFirefox = typeof InstallTrigger !== 'undefined';
// Safari 3.0+
isSafari = /constructor/i.test(window.HTMLElement) || (function (p) { return p.toString() === "[object SafariRemoteNotification]"; })(!window['safari'] || safari.pushNotification);
// Internet Explorer 6-11
isIE = /*#cc_on!#*/false || !!document.documentMode;
// Edge 20+
isEdge = !isIE && !!window.StyleMedia;
// Chrome 1+
isChrome = !!window.chrome && !!window.chrome.webstore;
// Blink engine detection
isBlink = (isChrome || isOpera) && !!window.CSS;
/* Results: */
console.log("isOpera", isOpera);
console.log("isFirefox", isFirefox);
console.log("isSafari", isSafari);
console.log("isIE", isIE);
console.log("isEdge", isEdge);
console.log("isChrome", isChrome);
console.log("isBlink", isBlink);
The beauty of this approach is that it relies on browser engine properties, so it covers even derivative browsers, such as Yandex or Vivaldi, which are practically compatible with the major browsers whose engines they use. The exception is Opera, which relies on user agent sniffing, but today (i.e. ver. 15 and up) even Opera is itself only a shell for Blink.
You can use try and catch to use the different browser error messages.
IE and edge were mixed up, but I used the duck typing from Rob W (based on this project here: https://www.khanacademy.org/computer-programming/i-have-opera/2395080328).
var getBrowser = function() {
try {
var e;
var f = e.width;
} catch(e) {
var err = e.toString();
if(err.indexOf("not an object") !== -1) {
return "safari";
} else if(err.indexOf("Cannot read") !== -1) {
return "chrome";
} else if(err.indexOf("e is undefined") !== -1) {
return "firefox";
} else if(err.indexOf("Unable to get property 'width' of undefined or null reference") !== -1) {
if(!(false || !!document.documentMode) && !!window.StyleMedia) {
return "edge";
} else {
return "IE";
}
} else if(err.indexOf("cannot convert e into object") !== -1) {
return "opera";
} else {
return undefined;
}
}
};
If you need to know what is the numeric version of some particular browser you can use the following snippet. Currently it will tell you the version of Chrome/Chromium/Firefox:
var match = $window.navigator.userAgent.match(/(?:Chrom(?:e|ium)|Firefox)\/([0-9]+)\./);
var ver = match ? parseInt(match[1], 10) : 0;
Detecting Browsers on Desktop and Mobile : Edge, Opera, Chrome, Safari, Firefox, IE
I did some changes in #nimesh code now it is working for Edge also,
and Opera issue fixed:
function getBrowserName() {
if ( navigator.userAgent.indexOf("Edge") > -1 && navigator.appVersion.indexOf('Edge') > -1 ) {
return 'Edge';
}
else if( navigator.userAgent.indexOf("Opera") != -1 || navigator.userAgent.indexOf('OPR') != -1 )
{
return 'Opera';
}
else if( navigator.userAgent.indexOf("Chrome") != -1 )
{
return 'Chrome';
}
else if( navigator.userAgent.indexOf("Safari") != -1)
{
return 'Safari';
}
else if( navigator.userAgent.indexOf("Firefox") != -1 )
{
return 'Firefox';
}
else if( ( navigator.userAgent.indexOf("MSIE") != -1 ) || (!!document.documentMode == true ) ) //IF IE > 10
{
return 'IE';
}
else
{
return 'unknown';
}
}
Thanks #nimesh user:2063564
There is also a less "hacky" method which works for all popular browsers.
Google has included a browser-check in their Closure Library. In particular, have a look at goog.userAgent and goog.userAgent.product. In this way, you are also up to date if something changes in the way the browsers present themselves (given that you always run the latest version of the closure compiler.)
UAParser is one of the JavaScript Library to identify browser, engine, OS, CPU, and device type/model from userAgent string.
There's an CDN available. Here, I have included a example code to detect browser using UAParser.
<!doctype html>
<html>
<head>
<script src="https://cdn.jsdelivr.net/npm/ua-parser-js#0/dist/ua-parser.min.js"></script>
<script type="text/javascript">
var parser = new UAParser();
var result = parser.getResult();
console.log(result.browser); // {name: "Chromium", version: "15.0.874.106"}
</script>
</head>
<body>
</body>
</html>
Now you can use the value of result.browser to conditionally program your page.
Source Tutorial: How to detect browser, engine, OS, CPU, and device using JavaScript?
You can use Detect-browser.js, JavaScript library that detects and prints an object of browser information including browser language/name, user agent, device type, user OS, referer, online/0ffline, user timezone, screen resolution, and cookie enabled.
Get it from here detect-browser.js
it will give you something like that:
Detecting Browser and Its version
This code snippet is based on the article from MDN. Where they gave a brief hint about various keywords that can be used to detect the browser name.
The data shown in the image above is not sufficient for detecting all the browsers e.g. userAgent of Firefox will have Fxios as a keyword rather than Firefox.
A few changes are also done to detect browsers like Edge and UCBrowser
The code is currently tested for the following browsers by changing userAgent with the help of dev-tools (How to change userAgent):
FireFox
Chrome
IE
Edge
Opera
Safari
UCBrowser
getBrowser = () => {
const userAgent = navigator.userAgent;
let browser = "unkown";
// Detect browser name
browser = (/ucbrowser/i).test(userAgent) ? 'UCBrowser' : browser;
browser = (/edg/i).test(userAgent) ? 'Edge' : browser;
browser = (/googlebot/i).test(userAgent) ? 'GoogleBot' : browser;
browser = (/chromium/i).test(userAgent) ? 'Chromium' : browser;
browser = (/firefox|fxios/i).test(userAgent) && !(/seamonkey/i).test(userAgent) ? 'Firefox' : browser;
browser = (/; msie|trident/i).test(userAgent) && !(/ucbrowser/i).test(userAgent) ? 'IE' : browser;
browser = (/chrome|crios/i).test(userAgent) && !(/opr|opera|chromium|edg|ucbrowser|googlebot/i).test(userAgent) ? 'Chrome' : browser;;
browser = (/safari/i).test(userAgent) && !(/chromium|edg|ucbrowser|chrome|crios|opr|opera|fxios|firefox/i).test(userAgent) ? 'Safari' : browser;
browser = (/opr|opera/i).test(userAgent) ? 'Opera' : browser;
// detect browser version
switch (browser) {
case 'UCBrowser': return `${browser}/${browserVersion(userAgent,/(ucbrowser)\/([\d\.]+)/i)}`;
case 'Edge': return `${browser}/${browserVersion(userAgent,/(edge|edga|edgios|edg)\/([\d\.]+)/i)}`;
case 'GoogleBot': return `${browser}/${browserVersion(userAgent,/(googlebot)\/([\d\.]+)/i)}`;
case 'Chromium': return `${browser}/${browserVersion(userAgent,/(chromium)\/([\d\.]+)/i)}`;
case 'Firefox': return `${browser}/${browserVersion(userAgent,/(firefox|fxios)\/([\d\.]+)/i)}`;
case 'Chrome': return `${browser}/${browserVersion(userAgent,/(chrome|crios)\/([\d\.]+)/i)}`;
case 'Safari': return `${browser}/${browserVersion(userAgent,/(safari)\/([\d\.]+)/i)}`;
case 'Opera': return `${browser}/${browserVersion(userAgent,/(opera|opr)\/([\d\.]+)/i)}`;
case 'IE': const version = browserVersion(userAgent,/(trident)\/([\d\.]+)/i);
// IE version is mapped using trident version
// IE/8.0 = Trident/4.0, IE/9.0 = Trident/5.0
return version ? `${browser}/${parseFloat(version) + 4.0}` : `${browser}/7.0`;
default: return `unknown/0.0.0.0`;
}
}
browserVersion = (userAgent,regex) => {
return userAgent.match(regex) ? userAgent.match(regex)[2] : null;
}
console.log(getBrowser());
Here is my customized solution.
const inBrowser = typeof window !== 'undefined'
const UA = inBrowser && window.navigator.userAgent.toLowerCase()
const isIE =
UA && /; msie|trident/i.test(UA) && !/ucbrowser/i.test(UA).test(UA)
const isEdge = UA && /edg/i.test(UA)
const isAndroid = UA && UA.indexOf('android') > 0
const isIOS = UA && /iphone|ipad|ipod|ios/i.test(UA)
const isChrome =
UA &&
/chrome|crios/i.test(UA) &&
!/opr|opera|chromium|edg|ucbrowser|googlebot/i.test(UA)
const isGoogleBot = UA && /googlebot/i.test(UA)
const isChromium = UA && /chromium/i.test(UA)
const isUcBrowser = UA && /ucbrowser/i.test(UA)
const isSafari =
UA &&
/safari/i.test(UA) &&
!/chromium|edg|ucbrowser|chrome|crios|opr|opera|fxios|firefox/i.test(UA)
const isFirefox = UA && /firefox|fxios/i.test(UA) && !/seamonkey/i.test(UA)
const isOpera = UA && /opr|opera/i.test(UA)
const isMobile =
/\b(BlackBerry|webOS|iPhone|IEMobile)\b/i.test(UA) ||
/\b(Android|Windows Phone|iPad|iPod)\b/i.test(UA)
const isSamsung = UA && /samsungbrowser/i.test(UA)
const isIPad = UA && /ipad/.test(UA)
const isIPhone = UA && /iphone/.test(UA)
const isIPod = UA && /ipod/.test(UA)
console.log({
UA,
isAndroid,
isChrome,
isChromium,
isEdge,
isFirefox,
isGoogleBot,
isIE,
isMobile,
isIOS,
isIPad,
isIPhone,
isIPod,
isOpera,
isSafari,
isSamsung,
isUcBrowser,
}
}
Chrome & Edge introduced a new User-Agent Client Hints API for this:
navigator.userAgentData.brands.map(item => item.brand).includes('Google Chrome')
Firefox & Safari don't support it yet unfortunately.
var BrowserDetect = {
init: function () {
this.browser = this.searchString(this.dataBrowser) || "Other";
this.version = this.searchVersion(navigator.userAgent) || this.searchVersion(navigator.appVersion) || "Unknown";
},
searchString: function (data) {
for (var i = 0; i < data.length; i++) {
var dataString = data[i].string;
this.versionSearchString = data[i].subString;
if (dataString.indexOf(data[i].subString) !== -1) {
return data[i].identity;
}
}
},
searchVersion: function (dataString) {
var index = dataString.indexOf(this.versionSearchString);
if (index === -1) {
return;
}
var rv = dataString.indexOf("rv:");
if (this.versionSearchString === "Trident" && rv !== -1) {
return parseFloat(dataString.substring(rv + 3));
} else {
return parseFloat(dataString.substring(index + this.versionSearchString.length + 1));
}
},
dataBrowser: [
{string: navigator.userAgent, subString: "Edge", identity: "MS Edge"},
{string: navigator.userAgent, subString: "MSIE", identity: "Explorer"},
{string: navigator.userAgent, subString: "Trident", identity: "Explorer"},
{string: navigator.userAgent, subString: "Firefox", identity: "Firefox"},
{string: navigator.userAgent, subString: "Opera", identity: "Opera"},
{string: navigator.userAgent, subString: "OPR", identity: "Opera"},
{string: navigator.userAgent, subString: "Chrome", identity: "Chrome"},
{string: navigator.userAgent, subString: "Safari", identity: "Safari"}
]
};
BrowserDetect.init();
var bv= BrowserDetect.browser;
if( bv == "Chrome"){
$("body").addClass("chrome");
}
else if(bv == "MS Edge"){
$("body").addClass("edge");
}
else if(bv == "Explorer"){
$("body").addClass("ie");
}
else if(bv == "Firefox"){
$("body").addClass("Firefox");
}
$(".relative").click(function(){
$(".oc").toggle('slide', { direction: 'left', mode: 'show' }, 500);
$(".oc1").css({
'width' : '100%',
'margin-left' : '0px',
});
});
To check for IE browser using following code.
console.log(/MSIE|Trident/.test(window.navigator.userAgent))
OR
var isIE = !!document.documentMode;
console.log(isIE)
Thanks
This combines both Rob's original answer and Pilau's update for 2016
var isOpera = !!window.opera || navigator.userAgent.indexOf(' OPR/') >= 0;
// Opera 8.0+ (UA detection to detect Blink/v8-powered Opera)
var isFirefox = typeof InstallTrigger !== 'undefined'; // Firefox 1.0+
var isSafari = Object.prototype.toString.call(window.HTMLElement).indexOf('Constructor') > 0;
// At least Safari 3+: "[object HTMLElementConstructor]"
var isChrome = !!window.chrome && !isOpera; // Chrome 1+
var isIE = /*#cc_on!#*/false || !!document.documentMode;
// Edge 20+
var isEdge = !isIE && !!window.StyleMedia;
// Chrome 1+
var output = 'Detecting browsers by ducktyping:<hr>';
output += 'isFirefox: ' + isFirefox + '<br>';
output += 'isChrome: ' + isChrome + '<br>';
output += 'isSafari: ' + isSafari + '<br>';
output += 'isOpera: ' + isOpera + '<br>';
output += 'isIE: ' + isIE + '<br>';
output += 'isIE Edge: ' + isEdge + '<br>';
document.body.innerHTML = output;
Here you find out which browser is it running.
function isValidBrowser(navigator){
var isChrome = navigator.indexOf('chrome'),
isFireFox= navigator.indexOf('firefox'),
isIE = navigator.indexOf('trident') ,
isValidChromeVer = parseInt(navigator.substring(isChrome+7, isChrome+8)) >= 4,
isValidFireForVer = parseInt(navigator.substring(isFireFox+8, isFireFox+9)) >= 3,
isValidIEVer = parseInt(navigator.substring(isIE+8, isIE+9)) >= 7;
if((isChrome > -1 && isValidChromeVer){ console.log("Chrome Browser")}
if(isFireFox > -1 && isValidFireForVer){ console.log("FireFox Browser")}
if(isIE > -1 && isValidIEVer)){ console.log("IE Browser")}
}
We can use below util methods
utils.isIE = function () {
var ver = navigator.userAgent;
return ver.indexOf("MSIE") !== -1 || ver.indexOf("Trident") !== -1; // need to check for Trident for IE11
};
utils.isIE32 = function () {
return (utils.isIE() && navigator.appVersion.indexOf('Win64') === -1);
};
utils.isChrome = function () {
return (window.chrome);
};
utils.isFF64 = function () {
var agent = navigator.userAgent;
return (agent.indexOf('Win64') >= 0 && agent.indexOf('Firefox') >= 0);
};
utils.isFirefox = function () {
return (navigator.userAgent.toLowerCase().indexOf('firefox') > -1);
};
const isChrome = /Chrome/.test(navigator.userAgent)
const isFirefox = /Firefox/.test(navigator.userAgent)
You can detect it like:
if (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)) {
alert('Firefox');
}
import getAgent, { getAccurateAgent } from "#egjs/agent";
const agent = getAgent();
getAccurateAgent().then((accurate_agent)=>{
console.log(agent,'accurate.');
})
console.log(agent);
https://github.com/naver/egjs-agent
This method is currently valid for detecting all browsers. I quoted the vue-element-admin template
export function fnBrowserDetect() {
var browserName = (function(agent) {
switch (true) {
case agent.indexOf('edge') > -1: return 'MS Edge'
case agent.indexOf('edg/') > -1: return 'Edge (chromium based)'
case agent.indexOf('opr') > -1 && !!window.opr: return 'Opera'
case agent.indexOf('chrome') > -1 && !!window.chrome: return 'Chrome'
case agent.indexOf('trident') > -1: return 'MS IE'
case agent.indexOf('firefox') > -1: return 'Mozilla Firefox'
case agent.indexOf('safari') > -1: return 'Safari'
default: return 'other'
}
})(window.navigator.userAgent.toLowerCase())
return browserName.toLowerCase()
}
var BrowserType;
(function (BrowserType) {
BrowserType["OPERA"] = "Opera";
BrowserType["OPERA2"] = "OPR";
BrowserType["EDGE"] = "Edg";
BrowserType["CHROME"] = "Chrome";
BrowserType["SAFARI"] = "Safari";
BrowserType["FIREFOX"] = "Firefox";
BrowserType["UNKNOWN"] = "unknown";
})(BrowserType || (BrowserType = {}));
const detectBrowser = () => {
return Object.values(BrowserType).find((browser) => navigator.userAgent.indexOf(browser) != -1);
};
console.log(detectBrowser());
Simple:
var OSName="Unknown OS";
if (navigator.appVersion.indexOf("Win")!=-1) OSName="Windows";
if (navigator.appVersion.indexOf("Mac")!=-1) OSName="MacOS";
if (navigator.appVersion.indexOf("X11")!=-1) OSName="UNIX";
if (navigator.appVersion.indexOf("Linux")!=-1) OSName="Linux";
if (navigator.appVersion.indexOf("Linux x86_64")!=-1) OSName="Ubuntu";
var nVer = navigator.appVersion;
var nAgt = navigator.userAgent;
var browserName = navigator.appName;
var fullVersion = ''+parseFloat(navigator.appVersion);
var majorVersion = parseInt(navigator.appVersion,10);
var nameOffset,verOffset,ix;
// In Opera, the true version is after "Opera" or after "Version"
if ((verOffset=nAgt.indexOf("Opera"))!=-1) {
browserName = "Opera";
fullVersion = nAgt.substring(verOffset+6);
if ((verOffset=nAgt.indexOf("Version"))!=-1)
fullVersion = nAgt.substring(verOffset+8);
}
// In MSIE, the true version is after "MSIE" in userAgent
else if ((verOffset=nAgt.indexOf("MSIE"))!=-1) {
browserName = "Microsoft Internet Explorer";
fullVersion = nAgt.substring(verOffset+5);
}
// In Chrome, the true version is after "Chrome"
else if ((verOffset=nAgt.indexOf("Chrome"))!=-1) {
browserName = "Chrome";
fullVersion = nAgt.substring(verOffset+7);
}
// In Safari, the true version is after "Safari" or after "Version"
else if ((verOffset=nAgt.indexOf("Safari"))!=-1) {
browserName = "Safari";
fullVersion = nAgt.substring(verOffset+7);
if ((verOffset=nAgt.indexOf("Version"))!=-1)
fullVersion = nAgt.substring(verOffset+8);
}
// In Firefox, the true version is after "Firefox"
else if ((verOffset=nAgt.indexOf("Firefox"))!=-1) {
browserName = "Firefox";
fullVersion = nAgt.substring(verOffset+8);
}
// In most other browsers, "name/version" is at the end of userAgent
else if ( (nameOffset=nAgt.lastIndexOf(' ')+1) <
(verOffset=nAgt.lastIndexOf('/')) )
{
browserName = nAgt.substring(nameOffset,verOffset);
fullVersion = nAgt.substring(verOffset+1);
if (browserName.toLowerCase()==browserName.toUpperCase()) {
browserName = navigator.appName;
}
}
// trim the fullVersion string at semicolon/space if present
if ((ix=fullVersion.indexOf(";"))!=-1)
fullVersion=fullVersion.substring(0,ix);
if ((ix=fullVersion.indexOf(" "))!=-1)
fullVersion=fullVersion.substring(0,ix);
majorVersion = parseInt(''+fullVersion,10);
if (isNaN(majorVersion)) {
fullVersion = ''+parseFloat(navigator.appVersion);
majorVersion = parseInt(navigator.appVersion,10);
}
document.write(''
+'Hey! i see you\'re using '+browserName+'! <br>'
+'The full version of it is '+fullVersion+'. <br>'
+'Your major version is '+majorVersion+', <br>'
+'And your "navigator.appName" is '+navigator.appName+'. <br>'
+'Your "navigator.userAgent" is '+navigator.userAgent+'. <br>'
)
document.write('And, your OS is '+OSName+'. <br>');
Simple, single line of JavaScript code will give you the name of browser:
function GetBrowser()
{
return navigator ? navigator.userAgent.toLowerCase() : "other";
}

How can you detect the version of a browser?

I've been searching around for code that would let me detect if the user visiting the website has Firefox 3 or 4. All I have found is code to detect the type of browser but not the version.
How can I detect the version of a browser like this?
You can see what the browser says, and use that information for logging or testing multiple browsers.
navigator.sayswho= (function(){
var ua= navigator.userAgent;
var tem;
var M= ua.match(/(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i) || [];
if(/trident/i.test(M[1])){
tem= /\brv[ :]+(\d+)/g.exec(ua) || [];
return 'IE '+(tem[1] || '');
}
if(M[1]=== 'Chrome'){
tem= ua.match(/\b(OPR|Edge)\/(\d+)/);
if(tem!= null) return tem.slice(1).join(' ').replace('OPR', 'Opera');
}
M= M[2]? [M[1], M[2]]: [navigator.appName, navigator.appVersion, '-?'];
if((tem= ua.match(/version\/(\d+)/i))!= null) M.splice(1, 1, tem[1]);
return M.join(' ');
})();
console.log(navigator.sayswho); // outputs: `Chrome 62`
This is an improvement on Kennebec's answer.
mbrowser=function(){
this.spec_string= navigator.userAgent;
this.name= this.get_name();
this.version= this.get_version();
};
mbrowser.prototype.get_name=function(){
var spec_string=this.spec_string;
var matches=spec_string.match(/(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i) || [];
// Work with the matches.
matches=matches[2]? [matches[1], matches[2]]: [navigator.appName, navigator.appVersion, '-?'];
// Trident.
if(/trident/i.test(matches[1])){
var temp=/\brv[ :]+(\d+)/g.exec(spec_string) || [];
return 'IE';
}
// Chrome.
if(matches[1]==='Chrome'){
var temp=spec_string.match(/\bOPR|Edge\/(\d+)/)
if(temp!=null) {return 'Opera';}
}
if((temp=spec_string.match(/version\/(\d+)/i))!=null){
matches.splice(1,1,temp[1]);
}
var name=matches[0];
return name;
};
mbrowser.prototype.get_version=function(){
var spec_string=this.spec_string;
var matches=spec_string.match(/(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i) || [];
// Work with the matches.
matches=matches[2]? [matches[1], matches[2]]: [navigator.appName, navigator.appVersion, '-?'];
// Trident.
if(/trident/i.test(matches[1])){
var temp=/\brv[ :]+(\d+)/g.exec(spec_string) || [];
var version=(temp[1]||'');
return version;
}
// Chrome.
if(matches[1]==='Chrome'){
var temp=spec_string.match(/\bOPR|Edge\/(\d+)/)
var version=temp[1];
if(temp!=null) {return version;}
}
if((temp=spec_string.match(/version\/(\d+)/i))!=null){
matches.splice(1,1,temp[1]);
}
var version=matches[1];
return version;
};
// m=module.
var browser=new mbrowser();
console.log(browser.name); // Chrome
console.log(browser.version); // 109
This code deduces browser name and number from the spec_string (navigator.userAgent). But there are all kinds of spec_strings out there with their respective browser name and number. And I'm not in a situation to check but a tiny proportion of them. It would be great if you could post a spec_string who's resulting browser name and number you know. I can then update the code accordingly.
I would then slowly build up a list of spec_string items in the following manner.
'spec_string1'=>[name,number],
'spec_string2'=>[name,number],
Then in the future, whenever a change is made to the code it can automatically be tested on all known spec_string conversions.
We can do this together.
Here are several prominent libraries that handle browser detection as of May 2019.
Bowser by lancedikson - 3,761★s - Last updated May 26, 2019 - 4.8KB
var result = bowser.getParser(window.navigator.userAgent);
console.log(result);
document.write("You are using " + result.parsedResult.browser.name +
" v" + result.parsedResult.browser.version +
" on " + result.parsedResult.os.name);
<script src="https://unpkg.com/bowser#2.4.0/es5.js"></script>
*supports Edge based on Chromium
Platform.js by bestiejs - 2,250★s - Last updated Oct 30, 2018 - 5.9KB
console.log(platform);
document.write("You are using " + platform.name +
" v" + platform.version +
" on " + platform.os);
<script src="https://cdnjs.cloudflare.com/ajax/libs/platform/1.3.5/platform.min.js"></script>
jQuery Browser by gabceb - 504★s - Last updated Nov 23, 2015 - 1.3KB
console.log($.browser)
document.write("You are using " + $.browser.name +
" v" + $.browser.versionNumber +
" on " + $.browser.platform);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-browser/0.1.0/jquery.browser.min.js"></script>
Detect.js (Archived) by darcyclarke - 522★s - Last updated Oct 26, 2015 - 2.9KB
var result = detect.parse(navigator.userAgent);
console.log(result);
document.write("You are using " + result.browser.family +
" v" + result.browser.version +
" on " + result.os.family);
<script src="https://cdnjs.cloudflare.com/ajax/libs/Detect.js/2.2.2/detect.min.js"></script>
Browser Detect (Archived) by QuirksMode - Last updated Nov 14, 2013 - 884B
console.log(BrowserDetect)
document.write("You are using " + BrowserDetect.browser +
" v" + BrowserDetect.version +
" on " + BrowserDetect.OS);
<script src="https://kylemit.github.io/libraries/libraries/BrowserDetect.js"></script>
Notable Mentions:
WhichBrowser - 1,355★s - Last updated Oct 2, 2018
Modernizr - 23,397★s - Last updated Jan 12, 2019 - To feed a fed horse, feature detection should drive any canIuse style questions. Browser detection is really just for providing customized images, download files, or instructions for individual browsers.
Further Reading
Stack Overflow - Browser detection in JavaScript?
Stack Overflow - How to detect Safari, Chrome, IE, Firefox and Opera browser?
This combines kennebec's (K) answer with Hermann Ingjaldsson's (H) answer:
Maintains original answer's minimal code. (K)
Works with Microsoft Edge (K)
Extends the navigator object instead of creating a new variable/object. (K)
Separates browser version and name into independent child objects. (H)
 
navigator.browserSpecs = (function(){
var ua = navigator.userAgent, tem,
M = ua.match(/(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i) || [];
if(/trident/i.test(M[1])){
tem = /\brv[ :]+(\d+)/g.exec(ua) || [];
return {name:'IE',version:(tem[1] || '')};
}
if(M[1]=== 'Chrome'){
tem = ua.match(/\b(OPR|Edge)\/(\d+)/);
if(tem != null) return {name:tem[1].replace('OPR', 'Opera'),version:tem[2]};
}
M = M[2]? [M[1], M[2]]: [navigator.appName, navigator.appVersion, '-?'];
if((tem = ua.match(/version\/(\d+)/i))!= null)
M.splice(1, 1, tem[1]);
return {name:M[0], version:M[1]};
})();
console.log(navigator.browserSpecs); //Object { name: "Firefox", version: "42" }
if (navigator.browserSpecs.name == 'Firefox') {
// Do something for Firefox.
if (navigator.browserSpecs.version > 42) {
// Do something for Firefox versions greater than 42.
}
}
else {
// Do something for all other browsers.
}
The bowser JavaScript library offers this functionality.
if (bowser.msie && bowser.version <= 6) {
alert('Hello China');
}
It seems to be well maintained.
Use this: http://www.quirksmode.org/js/detect.html
alert(BrowserDetect.browser); // will say "Firefox"
alert(BrowserDetect.version); // will say "3" or "4"
I was looking for a solution for myself, since jQuery 1.9.1 and above have removed the $.browser functionality. I came up with this little function that works for me.
It does need a global variable (I've called mine _browser) in order to check which browser it is. I've written a jsfiddle to illustrate how it can be used, of course it can be expanded for other browsers by just adding a test for _browser.foo, where foo is the name of the browser. I did just the popular ones.
detectBrowser()
_browser = {};
function detectBrowser() {
var uagent = navigator.userAgent.toLowerCase(),
match = '';
_browser.chrome = /webkit/.test(uagent) && /chrome/.test(uagent) &&
!/edge/.test(uagent);
_browser.firefox = /mozilla/.test(uagent) && /firefox/.test(uagent);
_browser.msie = /msie/.test(uagent) || /trident/.test(uagent) ||
/edge/.test(uagent);
_browser.safari = /safari/.test(uagent) && /applewebkit/.test(uagent) &&
!/chrome/.test(uagent);
_browser.opr = /mozilla/.test(uagent) && /applewebkit/.test(uagent) &&
/chrome/.test(uagent) && /safari/.test(uagent) &&
/opr/.test(uagent);
_browser.version = '';
for (x in _browser) {
if (_browser[x]) {
match = uagent.match(
new RegExp("(" + (x === "msie" ? "msie|edge" : x) + ")( |\/)([0-9]+)")
);
if (match) {
_browser.version = match[3];
} else {
match = uagent.match(new RegExp("rv:([0-9]+)"));
_browser.version = match ? match[1] : "";
}
break;
}
}
_browser.opera = _browser.opr;
delete _browser.opr;
}
detectBrowser();
console.log(_browser)
To check if the current browser is Opera you would do
if (_browser.opera) { // Opera specific code }
Edit Fixed the formatting, fixed the detection for IE11 and Opera/Chrome, changed to browserResult from result. Now the order of the _browser keys doesn't matter. Updated jsFiddle link.
2015/08/11 Edit Added new testcase for Internet Explorer 12 (EDGE), fixed a small regexp problem. Updated jsFiddle link.
function BrowserCheck()
{
var N= navigator.appName, ua= navigator.userAgent, tem;
var M= ua.match(/(opera|chrome|safari|firefox|msie|trident)\/?\s*(\.?\d+(\.\d+)*)/i);
if(M && (tem= ua.match(/version\/([\.\d]+)/i))!= null) {M[2]=tem[1];}
M= M? [M[1], M[2]]: [N, navigator.appVersion,'-?'];
return M;
}
This will return an array, first element is the browser name, second element is the complete version number in string format.
This is a Update on Fzs2 & kennebec For New Edge Chromium
function get_browser() {
var ua=navigator.userAgent,tem,M=ua.match(/(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i) || [];
if(/trident/i.test(M[1])){
tem=/\brv[ :]+(\d+)/g.exec(ua) || [];
return {name:'IE',version:(tem[1]||'')};
}
if(M[1]==='Chrome'){
tem=ua.match(/\bEdg\/(\d+)/)
if(tem!=null) {return {name:'Edge(Chromium)', version:tem[1]};}
tem=ua.match(/\bOPR\/(\d+)/)
if(tem!=null) {return {name:'Opera', version:tem[1]};}
}
M=M[2]? [M[1], M[2]]: [navigator.appName, navigator.appVersion, '-?'];
if((tem=ua.match(/version\/(\d+)/i))!=null) {M.splice(1,1,tem[1]);}
return {
name: M[0],
version: M[1]
};
}
var browser=get_browser(); // browser.name = 'Edge(Chromium)'
// browser.version = '86'
console.log(browser);
In pure Javascript you can do a RegExp match on the navigator.userAgent to find the Firefox version:
var uMatch = navigator.userAgent.match(/Firefox\/(.*)$/),
ffVersion;
if (uMatch && uMatch.length > 1) {
ffVersion = uMatch[1];
}
ffVersion will be undefined if not a Firefox browser.
See working example →
jQuery can handle this quite nice (jQuery.browser)
var ua = $.browser;
if ( ua.mozilla && ua.version.slice(0,3) == "1.9" ) {
alert( "Do stuff for firefox 3" );
}
EDIT: As Joshua wrote in his comment below, jQuery.browser property is no longer supported in jQuery since version 1.9 (read jQuery 1.9 release notes for more details).
jQuery development team recommends using more complete approach like adapting UI with Modernizr library.
Look at navigator.userAgent - Firefox/xxx.xxx.xxx is specified right at the end.
<script type="text/javascript">
var version = navigator.appVersion;
alert(version);
</script>
I wrote a version detector based on Hermann Ingjaldsson's answer, but more robust and which returns an object with name/version data in it. It covers the major browsers but I don't bother with the plethora of mobile ones and minor ones:
function getBrowserData(nav) {
var data = {};
var ua = data.uaString = nav.userAgent;
var browserMatch = ua.match(/(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*([\d\.]+)/i) || [];
if (browserMatch[1]) { browserMatch[1] = browserMatch[1].toLowerCase(); }
var operaMatch = browserMatch[1] === 'chrome';
if (operaMatch) { operaMatch = ua.match(/\bOPR\/([\d\.]+)/); }
if (/trident/i.test(browserMatch[1])) {
var msieMatch = /\brv[ :]+([\d\.]+)/g.exec(ua) || [];
data.name = 'msie';
data.version = msieMatch[1];
}
else if (operaMatch) {
data.name = 'opera';
data.version = operaMatch[1];
}
else if (browserMatch[1] === 'safari') {
var safariVersionMatch = ua.match(/version\/([\d\.]+)/i);
data.name = 'safari';
data.version = safariVersionMatch[1];
}
else {
data.name = browserMatch[1];
data.version = browserMatch[2];
}
var versionParts = [];
if (data.version) {
var versionPartsMatch = data.version.match(/(\d+)/g) || [];
for (var i=0; i < versionPartsMatch.length; i++) {
versionParts.push(versionPartsMatch[i]);
}
if (versionParts.length > 0) { data.majorVersion = versionParts[0]; }
}
data.name = data.name || '(unknown browser name)';
data.version = {
full: data.version || '(unknown full browser version)',
parts: versionParts,
major: versionParts.length > 0 ? versionParts[0] : '(unknown major browser version)'
};
return data;
};
It can then be used like this:
var brData = getBrowserData(window.navigator || navigator);
console.log('name: ' + brData.name);
console.log('major version: ' + brData.version.major);
// etc.
For this you need to check the value of navigator.appVersion or navigator.userAgent
Try using:
console.log(navigator.appVersion)
var nVer = navigator.appVersion;
var nAgt = navigator.userAgent;
var browserName = navigator.appName;
var fullVersion = ''+parseFloat(navigator.appVersion);
var majorVersion = parseInt(navigator.appVersion,10);
var nameOffset,verOffset,ix;
// In Opera, the true version is after "Opera" or after "Version"
if ((verOffset=nAgt.indexOf("Opera"))!=-1) {
browserName = "Opera";
fullVersion = nAgt.substring(verOffset+6);
if ((verOffset=nAgt.indexOf("Version"))!=-1)
fullVersion = nAgt.substring(verOffset+8);
}
// In MSIE, the true version is after "MSIE" in userAgent
else if ((verOffset=nAgt.indexOf("MSIE"))!=-1) {
browserName = "Microsoft Internet Explorer";
fullVersion = nAgt.substring(verOffset+5);
}
// In Chrome, the true version is after "Chrome"
else if ((verOffset=nAgt.indexOf("Chrome"))!=-1) {
browserName = "Chrome";
fullVersion = nAgt.substring(verOffset+7);
}
// In Safari, the true version is after "Safari" or after "Version"
else if ((verOffset=nAgt.indexOf("Safari"))!=-1) {
browserName = "Safari";
fullVersion = nAgt.substring(verOffset+7);
if ((verOffset=nAgt.indexOf("Version"))!=-1)
fullVersion = nAgt.substring(verOffset+8);
}
// In Firefox, the true version is after "Firefox"
else if ((verOffset=nAgt.indexOf("Firefox"))!=-1) {
browserName = "Firefox";
fullVersion = nAgt.substring(verOffset+8);
}
// In most other browsers, "name/version" is at the end of userAgent
else if ( (nameOffset=nAgt.lastIndexOf(' ')+1) <
(verOffset=nAgt.lastIndexOf('/')) )
{
browserName = nAgt.substring(nameOffset,verOffset);
fullVersion = nAgt.substring(verOffset+1);
if (browserName.toLowerCase()==browserName.toUpperCase()) {
browserName = navigator.appName;
}
}
// trim the fullVersion string at semicolon/space if present
if ((ix=fullVersion.indexOf(";"))!=-1)
fullVersion=fullVersion.substring(0,ix);
if ((ix=fullVersion.indexOf(" "))!=-1)
fullVersion=fullVersion.substring(0,ix);
majorVersion = parseInt(''+fullVersion,10);
if (isNaN(majorVersion)) {
fullVersion = ''+parseFloat(navigator.appVersion);
majorVersion = parseInt(navigator.appVersion,10);
}
document.write(''
+'Browser name = '+browserName+'<br>'
+'Full version = '+fullVersion+'<br>'
+'Major version = '+majorVersion+'<br>'
+'navigator.appName = '+navigator.appName+'<br>'
+'navigator.userAgent = '+navigator.userAgent+'<br>'
)
See the demo here..http://jsfiddle.net/hw4jM/3/
Detecting Browser and Its version
This code snippet is based on the article from MDN. Where they gave a brief hint about various keywords that can be used to detect the browser name.
I have done few changes to detect browsers like Edge and UCBrowser
getBrowser = () => {
const userAgent = navigator.userAgent;
let browser = "unkown";
// Detect browser name
browser = (/ucbrowser/i).test(userAgent) ? 'UCBrowser' : browser;
browser = (/edg/i).test(userAgent) ? 'Edge' : browser;
browser = (/googlebot/i).test(userAgent) ? 'GoogleBot' : browser;
browser = (/chromium/i).test(userAgent) ? 'Chromium' : browser;
browser = (/firefox|fxios/i).test(userAgent) && !(/seamonkey/i).test(userAgent) ? 'Firefox' : browser;
browser = (/; msie|trident/i).test(userAgent) && !(/ucbrowser/i).test(userAgent) ? 'IE' : browser;
browser = (/chrome|crios/i).test(userAgent) && !(/opr|opera|chromium|edg|ucbrowser|googlebot/i).test(userAgent) ? 'Chrome' : browser;;
browser = (/safari/i).test(userAgent) && !(/chromium|edg|ucbrowser|chrome|crios|opr|opera|fxios|firefox/i).test(userAgent) ? 'Safari' : browser;
browser = (/opr|opera/i).test(userAgent) ? 'Opera' : browser;
// detect browser version
switch (browser) {
case 'UCBrowser': return `${browser}/${browserVersion(userAgent,/(ucbrowser)\/([\d\.]+)/i)}`;
case 'Edge': return `${browser}/${browserVersion(userAgent,/(edge|edga|edgios|edg)\/([\d\.]+)/i)}`;
case 'GoogleBot': return `${browser}/${browserVersion(userAgent,/(googlebot)\/([\d\.]+)/i)}`;
case 'Chromium': return `${browser}/${browserVersion(userAgent,/(chromium)\/([\d\.]+)/i)}`;
case 'Firefox': return `${browser}/${browserVersion(userAgent,/(firefox|fxios)\/([\d\.]+)/i)}`;
case 'Chrome': return `${browser}/${browserVersion(userAgent,/(chrome|crios)\/([\d\.]+)/i)}`;
case 'Safari': return `${browser}/${browserVersion(userAgent,/(safari)\/([\d\.]+)/i)}`;
case 'Opera': return `${browser}/${browserVersion(userAgent,/(opera|opr)\/([\d\.]+)/i)}`;
case 'IE': const version = browserVersion(userAgent,/(trident)\/([\d\.]+)/i);
// IE version is mapped using trident version
// IE/8.0 = Trident/4.0, IE/9.0 = Trident/5.0
return version ? `${browser}/${parseFloat(version) + 4.0}` : `${browser}/7.0`;
default: return `unknown/0.0.0.0`;
}
}
browserVersion = (userAgent,regex) => {
return userAgent.match(regex) ? userAgent.match(regex)[2] : null;
}
console.log(getBrowser());
I have made a script in ASP code to detect browser, browser version, OS and OS version.
The reason for me to do this in ASP was because i want to store the data in a log-database.
So I had to detect the browser serverside.
Here is the code:
on error resume next
ua = lcase(Request.ServerVariables("HTTP_USER_AGENT"))
moz = instr(ua,"mozilla")
ffx = instr(ua,"firefox")
saf = instr(ua,"safari")
crm = instr(ua,"chrome")
max = instr(ua,"maxthon")
opr = instr(ua,"opera")
ie4 = instr(ua,"msie 4")
ie5 = instr(ua,"msie 5")
ie6 = instr(ua,"msie 6")
ie7 = instr(ua,"msie 7")
ie8 = instr(ua,"trident/4.0")
ie9 = instr(ua,"trident/5.0")
if moz>0 then
BrowserType = "Mozilla"
BrVer = mid(ua,moz+8,(instr(moz,ua," ")-(moz+8)))
end if
if ffx>0 then
BrowserType = "FireFox"
BrVer = mid(ua,ffx+8)
end if
if saf>0 then
BrowserType = "Safari"
BrVerPlass = instr(ua,"version")
BrVer = mid(ua,BrVerPlass+8,(instr(BrVerPlass,ua," ")-(BrVerPlass+8)))
end if
if crm>0 then
BrowserType = "Chrome"
BrVer = mid(ua,crm+7,(instr(crm,ua," ")-(crm+7)))
end if
if max>0 then
BrowserType = "Maxthon"
BrVer = mid(ua,max+8,(instr(max,ua," ")-(max+8)))
end if
if opr>0 then
BrowserType = "Opera"
BrVerPlass = instr(ua,"presto")
BrVer = mid(ua,BrVerPlass+7,(instr(BrVerPlass,ua," ")-(BrVerPlass+7)))
end if
if ie4>0 then
BrowserType = "Internet Explorer"
BrVer = "4"
end if
if ie5>0 then
BrowserType = "Internet Explorer"
BrVer = "5"
end if
if ie6>0 then
BrowserType = "Internet Explorer"
BrVer = "6"
end if
if ie7>0 then
BrowserType = "Internet Explorer"
BrVer = "7"
end if
if ie8>0 then
BrowserType = "Internet Explorer"
BrVer = "8"
if ie7>0 then BrVer = BrVer & " (in IE7 compability mode)"
end if
if ie9>0 then
BrowserType = "Internet Explorer"
BrVer = "9"
if ie7>0 then BrVer = BrVer & " (in IE7 compability mode)"
if ie8>0 then BrVer = BrVer & " (in IE8 compability mode)"
end if
OSSel = mid(ua,instr(ua,"(")+1,(instr(ua,";")-instr(ua,"("))-1)
OSver = mid(ua,instr(ua,";")+1,(instr(ua,")")-instr(ua,";"))-1)
if BrowserType = "Internet Explorer" then
OSStart = instr(ua,";")
OSStart = instr(OSStart+1,ua,";")
OSStopp = instr(OSStart+1,ua,";")
OSsel = mid(ua,OSStart+2,(OSStopp-OSStart)-2)
end if
Select case OSsel
case "windows nt 6.1"
OS = "Windows"
OSver = "7"
case "windows nt 6.0"
OS = "Windows"
OSver = "Vista"
case "windows nt 5.2"
OS = "Windows"
OSver = "Srv 2003 / XP x64"
case "windows nt 5.1"
OS = "Windows"
OSver = "XP"
case else
OS = OSSel
End select
Response.write "<br>" & ua & "<br>" & BrowserType & "<br>" & BrVer & "<br>" & OS & "<br>" & OSver & "<br>"
'Use the variables here for whatever you need........
This page seems to have a pretty nice snippet which only uses the appString and appVersion property as a last resort as it claims them to be unreliable with certain browsers.
The code on the page is as follows:
var nVer = navigator.appVersion;
var nAgt = navigator.userAgent;
var browserName = navigator.appName;
var fullVersion = ''+parseFloat(navigator.appVersion);
var majorVersion = parseInt(navigator.appVersion,10);
var nameOffset,verOffset,ix;
// In Opera 15+, the true version is after "OPR/"
if ((verOffset=nAgt.indexOf("OPR/"))!=-1) {
browserName = "Opera";
fullVersion = nAgt.substring(verOffset+4);
}
// In older Opera, the true version is after "Opera" or after "Version"
else if ((verOffset=nAgt.indexOf("Opera"))!=-1) {
browserName = "Opera";
fullVersion = nAgt.substring(verOffset+6);
if ((verOffset=nAgt.indexOf("Version"))!=-1)
fullVersion = nAgt.substring(verOffset+8);
}
// In MSIE, the true version is after "MSIE" in userAgent
else if ((verOffset=nAgt.indexOf("MSIE"))!=-1) {
browserName = "Microsoft Internet Explorer";
fullVersion = nAgt.substring(verOffset+5);
}
// In Chrome, the true version is after "Chrome"
else if ((verOffset=nAgt.indexOf("Chrome"))!=-1) {
browserName = "Chrome";
fullVersion = nAgt.substring(verOffset+7);
}
// In Safari, the true version is after "Safari" or after "Version"
else if ((verOffset=nAgt.indexOf("Safari"))!=-1) {
browserName = "Safari";
fullVersion = nAgt.substring(verOffset+7);
if ((verOffset=nAgt.indexOf("Version"))!=-1)
fullVersion = nAgt.substring(verOffset+8);
}
// In Firefox, the true version is after "Firefox"
else if ((verOffset=nAgt.indexOf("Firefox"))!=-1) {
browserName = "Firefox";
fullVersion = nAgt.substring(verOffset+8);
}
// In most other browsers, "name/version" is at the end of userAgent
else if ( (nameOffset=nAgt.lastIndexOf(' ')+1) <
(verOffset=nAgt.lastIndexOf('/')) )
{
browserName = nAgt.substring(nameOffset,verOffset);
fullVersion = nAgt.substring(verOffset+1);
if (browserName.toLowerCase()==browserName.toUpperCase()) {
browserName = navigator.appName;
}
}
// trim the fullVersion string at semicolon/space if present
if ((ix=fullVersion.indexOf(";"))!=-1)
fullVersion=fullVersion.substring(0,ix);
if ((ix=fullVersion.indexOf(" "))!=-1)
fullVersion=fullVersion.substring(0,ix);
majorVersion = parseInt(''+fullVersion,10);
if (isNaN(majorVersion)) {
fullVersion = ''+parseFloat(navigator.appVersion);
majorVersion = parseInt(navigator.appVersion,10);
}
document.write(''
+'Browser name = '+browserName+'<br>'
+'Full version = '+fullVersion+'<br>'
+'Major version = '+majorVersion+'<br>'
+'navigator.appName = '+navigator.appName+'<br>'
+'navigator.userAgent = '+navigator.userAgent+'<br>'
)
Adding my own implementation of Hermann's answer. I needed OS detection so that's been added. Also includes some ES6 code (because we have a transpiler) that you might need to ES5-ify.
detectClient() {
let nav = navigator.appVersion,
os = 'unknown',
client = (() => {
let agent = navigator.userAgent,
engine = agent.match(/(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i) || [],
build;
if(/trident/i.test(engine[1])){
build = /\brv[ :]+(\d+)/g.exec(agent) || [];
return {browser:'IE', version:(build[1] || '')};
}
if(engine[1] === 'Chrome'){
build = agent.match(/\bOPR\/(\d+)/);
if(build !== null) {
return {browser: 'Opera', version: build[1]};
}
}
engine = engine[2] ? [engine[1], engine[2]] : [navigator.appName, nav, '-?'];
if((build = agent.match(/version\/(\d+)/i)) !== null) {
engine.splice(1, 1, build[1]);
}
return {
browser: engine[0],
version: engine[1]
};
})();
switch (true) {
case nav.indexOf('Win') > -1:
os = 'Windows';
break;
case nav.indexOf('Mac') > -1:
os = 'MacOS';
break;
case nav.indexOf('X11') > -1:
os = 'UNIX';
break;
case nav.indexOf('Linux') > -1:
os = 'Linux';
break;
}
client.os = os;
return client;
}
Returns: Object {browser: "Chrome", version: "50", os: "UNIX"}
Here this has better compatibility then #kennebec snippet;
will return browser name and version (returns 72 instead of 72.0.3626.96).
Tested on Safari, Chrome, Opera, Firefox, IE, Edge, UCBrowser, also on mobile.
function browser() {
var userAgent = navigator.userAgent,
match = userAgent.match(/(opera|chrome|crios|safari|ucbrowser|firefox|msie|trident(?=\/))\/?\s*(\d+)/i) || [],
result = {},
tem;
if (/trident/i.test(match[1])) {
tem = /\brv[ :]+(\d+)/g.exec(userAgent) || [];
result.name = "Internet Explorer";
} else if (match[1] === "Chrome") {
tem = userAgent.match(/\b(OPR|Edge)\/(\d+)/);
if (tem && tem[1]) {
result.name = tem[0].indexOf("Edge") === 0 ? "Edge" : "Opera";
}
}
if (!result.name) {
tem = userAgent.match(/version\/(\d+)/i); // iOS support
result.name = match[0].replace(/\/.*/, "");
if (result.name.indexOf("MSIE") === 0) {
result.name = "Internet Explorer";
}
if (userAgent.match("CriOS")) {
result.name = "Chrome";
}
}
if (tem && tem.length) {
match[match.length - 1] = tem[tem.length - 1];
}
result.version = Number(match[match.length - 1]);
return result;
}
I want to share this code I wrote for the issue I had to resolve. It was tested in most of the major browsers and works like a charm, for me!
It may seems that this code is very similar to the other answers but it modifyed so that I can use it insted of the browser object in jquery which missed for me recently, of course it is a combination from the above codes, with little improvements from my part I made:
(function($, ua){
var M = ua.match(/(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i) || [],
tem,
res;
if(/trident/i.test(M[1])){
tem = /\brv[ :]+(\d+)/g.exec(ua) || [];
res = 'IE ' + (tem[1] || '');
}
else if(M[1] === 'Chrome'){
tem = ua.match(/\b(OPR|Edge)\/(\d+)/);
if(tem != null)
res = tem.slice(1).join(' ').replace('OPR', 'Opera');
else
res = [M[1], M[2]];
}
else {
M = M[2]? [M[1], M[2]] : [navigator.appName, navigator.appVersion, '-?'];
if((tem = ua.match(/version\/(\d+)/i)) != null) M = M.splice(1, 1, tem[1]);
res = M;
}
res = typeof res === 'string'? res.split(' ') : res;
$.browser = {
name: res[0],
version: res[1],
msie: /msie|ie/i.test(res[0]),
firefox: /firefox/i.test(res[0]),
opera: /opera/i.test(res[0]),
chrome: /chrome/i.test(res[0]),
edge: /edge/i.test(res[0])
}
})(typeof jQuery != 'undefined'? jQuery : window.$, navigator.userAgent);
console.log($.browser.name, $.browser.version, $.browser.msie);
// if IE 11 output is: IE 11 true
navigator.sayswho= (function(){
var ua= navigator.userAgent, tem,
M= ua.match(/(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i) || [];
if(/trident/i.test(M[1])){
tem= /\brv[ :]+(\d+)/g.exec(ua) || [];
return 'IE '+(tem[1] || '');
}
if(M[1]=== 'Chrome'){
tem= ua.match(/\b(OPR|Edge)\/(\d+)/);
if(tem!= null) return tem.slice(1).join(' ').replace('OPR', 'Opera');
}
M= M[2]? [M[1], M[2]]: [navigator.appName, navigator.appVersion, '-?'];
if((tem= ua.match(/version\/(\d+)/i))!= null) M.splice(1, 1, tem[1]);
return M.join(' ');
})();
console.log(navigator.sayswho); // outputs: `Chrome 62`
I use this to get de Name and number (int) of the version of the actual browser:
function getInfoBrowser() {
var ua = navigator.userAgent, tem,
M = ua.match(/(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i) || [];
if (/trident/i.test(M[1])) {
tem = /\brv[ :]+(\d+)/g.exec(ua) || [];
return { name: 'Explorer', version: parseInt((tem[1] || '')) };
}
if (M[1] === 'Chrome') {
tem = ua.match(/\b(OPR|Edge)\/(\d+)/);
if (tem != null) { let app = tem.slice(1).toString().split(','); return { name: app[0].replace('OPR', 'Opera'), version: parseInt(app[1]) }; }
}
M = M[2] ? [M[1], M[2]] : [navigator.appName, navigator.appVersion, '-?'];
if ((tem = ua.match(/version\/(\d+)/i)) != null) M.splice(1, 1, tem[1]);
return {
name: M[0],
version: parseInt(M[1])
};
}
function getBrowser(){
let info = getInfoBrowser();
$("#i-name").html(info.name);
$("#i-version").html(info.version);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="button" onclick="getBrowser();" value="Get Info Browser"/>
<hr/>
Name: <span id="i-name"></span><br/>
Version: <span id="i-version"></span>
This run in
Chrome ; Firefox ; Safari ; Internet Explorer (>= 9) ; Opera ; Edge
For me.
For any PWA application using angular you can put the code to check if browser is supported or not in body section of index.html -
<body>
<div id="browser"></div>
<script>
var operabrowser = true;
operabrowser = (navigator.userAgent.indexOf('Opera Mini') > -1);
if (operabrowser) {
txt = "<p>Browser not supported use different browser...</p>";
document.getElementById("browser").innerHTML = txt;
}
</script>
</body>
var ua = navigator.userAgent;
if (/Firefox\//.test(ua))
var Firefox = /Firefox\/([0-9\.A-z]+)/.exec(ua)[1];
I wrote this for my needs.
It get info like if is a mobile device or if has a retina display
try it
var nav = {
isMobile:function(){
return (navigator.userAgent.match(/iPhone|iPad|iPod|Android|BlackBerry|Opera Mini|IEMobile/i) != null);
},
isDesktop:function(){
return (navigator.userAgent.match(/iPhone|iPad|iPod|Android|BlackBerry|Opera Mini|IEMobile/i) == null);
},
isAndroid: function() {
return navigator.userAgent.match(/Android/i);
},
isBlackBerry: function() {
return navigator.userAgent.match(/BlackBerry/i);
},
isIOS: function() {
return navigator.userAgent.match(/iPhone|iPad|iPod/i);
},
isOpera: function() {
return navigator.userAgent.match(/Opera Mini/i);
},
isWindows: function() {
return navigator.userAgent.match(/IEMobile/i);
},
isRetina:function(){
return window.devicePixelRatio && window.devicePixelRatio > 1;
},
isIPad:function(){
isIPad = (/ipad/gi).test(navigator.platform);
return isIPad;
},
isLandscape:function(){
if(window.innerHeight < window.innerWidth){
return true;
}
return false;
},
getIOSVersion:function(){
if(this.isIOS()){
var OSVersion = navigator.appVersion.match(/OS (\d+_\d+)/i);
OSVersion = OSVersion[1] ? +OSVersion[1].replace('_', '.') : 0;
return OSVersion;
}
else
return false;
},
isStandAlone:function(){
if(_.is(navigator.standalone))
return navigator.standalone;
return false;
},
isChrome:function(){
var isChrome = (/Chrome/gi).test(navigator.appVersion);
var isSafari = (/Safari/gi).test(navigator.appVersion)
return isChrome && isSafari;
},
isSafari:function(){
var isSafari = (/Safari/gi).test(navigator.appVersion)
var isChrome = (/Chrome/gi).test(navigator.appVersion)
return !isChrome && isSafari;
}
}
I use this piece of javascript code based on what I could find in another posts.
var browserHelper = function () {
var self = {};
/// IE 6+
self.isIEBrowser = function () {
return /*#cc_on!#*/false || !!document.documentMode;
};
/// Opera 8.0+
self.isOperaBrowser = function () {
return (!!window.opr && !!opr.addons)
|| !!window.opera
|| navigator.userAgent.indexOf(' OPR/') >= 0;
};
/// Firefox 1.0+
self.isFirefoxBrowser = function () {
return typeof InstallTrigger !== 'undefined';
};
/// Safari 3.0+
self.isSafariBrowser = function () {
return /constructor/i.test(window.HTMLElement)
|| (function (p) { return p.toString() === "[object SafariRemoteNotification]"; })(!window['safari'] || (typeof safari !== 'undefined' && window['safari'].pushNotification));
};
/// Edge 20+
self.isEdgeBrowser = function () {
return !self.isIEBrowser() && !!window.StyleMedia;
};
/// Chrome 1 - 87
self.isChromeBrowser = function () {
return (!!window.chrome && (!!window.chrome.webstore || !!window.chrome.runtime))
|| (navigator.userAgent.indexOf("Chrome") > -1) && !self.isOperaBrowser();
};
/// Edge (based on chromium)
self.isEdgeChromiumBrowser = function () {
return self.isChromeBrowser() && (navigator.userAgent.indexOf("Edg") != -1);
};
/// Blink
self.isBlinkBasedOnBrowser = function () {
return (self.isChromeBrowser() || self.isOperaBrowser()) && !!window.CSS;
};
/// Returns the name of the navigator
self.browserName = function () {
if (self.isOperaBrowser()) return "Opera";
if (self.isEdgeBrowser()) return "Edge";
if (self.isEdgeChromiumBrowser()) return "Edge (based on chromium)";
if (self.isFirefoxBrowser()) return "Firefox";
if (self.isIEBrowser()) return "Internet Explorer";
if (self.isSafariBrowser()) return "Safari";
if (self.isChromeBrowser()) return "Chrome";
return "Unknown";
};
return self;
};
var bName = document.getElementById('browserName');
bName.innerText = browserHelper().browserName();
#browserName {
font-family: Arial, Verdana;
font-size: 1.2rem;
color: #ff8000;
text-align: center;
border: 2px solid #ff8000;
border-radius: .5rem;
padding: .5rem;
max-width: 25%;
margin: auto;
}
<div id="browserName"></div>
For chromium browser is so simple.
Version : navigator.userAgentData.brands[0].version
Browser Name : navigator.userAgentData.brands[0].brand
This got me the version of Firefox,
let versionNumber = parseInt(window.navigator.userAgent.match(/Firefox\/([0-
9]+)\./)[1]);

Browser detection in JavaScript? [duplicate]

This question already has answers here:
How can you detect the version of a browser?
(34 answers)
Closed 5 years ago.
How do I determine the exact browser and version using JavaScript?
navigator.saysWho = (() => {
const { userAgent } = navigator
let match = userAgent.match(/(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i) || []
let temp
if (/trident/i.test(match[1])) {
temp = /\brv[ :]+(\d+)/g.exec(userAgent) || []
return `IE ${temp[1] || ''}`
}
if (match[1] === 'Chrome') {
temp = userAgent.match(/\b(OPR|Edge)\/(\d+)/)
if (temp !== null) {
return temp.slice(1).join(' ').replace('OPR', 'Opera')
}
temp = userAgent.match(/\b(Edg)\/(\d+)/)
if (temp !== null) {
return temp.slice(1).join(' ').replace('Edg', 'Edge (Chromium)')
}
}
match = match[2] ? [ match[1], match[2] ] : [ navigator.appName, navigator.appVersion, '-?' ]
temp = userAgent.match(/version\/(\d+)/i)
if (temp !== null) {
match.splice(1, 1, temp[1])
}
return match.join(' ')
})()
console.log(navigator.saysWho) // outputs: `Chrome 89`
As the name implies, this will tell you the name and version number supplied by the browser.
It is handy for sorting test and error results, when you are testing new code on multiple browsers.
I recommend using the tiny javascript library Bowser. It is based on the navigator.userAgent and quite well tested for all browsers including iphone, android etc.
https://github.com/ded/bowser
You can use simply say:
if (bowser.msie && bowser.version <= 6) {
alert('Hello IE');
} else if (bowser.firefox){
alert('Hello Foxy');
} else if (bowser.chrome){
alert('Hello Chrome');
} else if (bowser.safari){
alert('Hello Safari');
} else if(bowser.iphone || bowser.android){
alert('Hello mobile');
}
This is something I wrote to get client info
var ua = navigator.userAgent.toLowerCase();
var check = function(r) {
return r.test(ua);
};
var DOC = document;
var isStrict = DOC.compatMode == "CSS1Compat";
var isOpera = check(/opera/);
var isChrome = check(/chrome/);
var isWebKit = check(/webkit/);
var isSafari = !isChrome && check(/safari/);
var isSafari2 = isSafari && check(/applewebkit\/4/); // unique to
// Safari 2
var isSafari3 = isSafari && check(/version\/3/);
var isSafari4 = isSafari && check(/version\/4/);
var isIE = !isOpera && check(/msie/);
var isIE7 = isIE && check(/msie 7/);
var isIE8 = isIE && check(/msie 8/);
var isIE6 = isIE && !isIE7 && !isIE8;
var isGecko = !isWebKit && check(/gecko/);
var isGecko2 = isGecko && check(/rv:1\.8/);
var isGecko3 = isGecko && check(/rv:1\.9/);
var isBorderBox = isIE && !isStrict;
var isWindows = check(/windows|win32/);
var isMac = check(/macintosh|mac os x/);
var isAir = check(/adobeair/);
var isLinux = check(/linux/);
var isSecure = /^https/i.test(window.location.protocol);
var isIE7InIE8 = isIE7 && DOC.documentMode == 7;
var jsType = '', browserType = '', browserVersion = '', osName = '';
var ua = navigator.userAgent.toLowerCase();
var check = function(r) {
return r.test(ua);
};
if(isWindows){
osName = 'Windows';
if(check(/windows nt/)){
var start = ua.indexOf('windows nt');
var end = ua.indexOf(';', start);
osName = ua.substring(start, end);
}
} else {
osName = isMac ? 'Mac' : isLinux ? 'Linux' : 'Other';
}
if(isIE){
browserType = 'IE';
jsType = 'IE';
var versionStart = ua.indexOf('msie') + 5;
var versionEnd = ua.indexOf(';', versionStart);
browserVersion = ua.substring(versionStart, versionEnd);
jsType = isIE6 ? 'IE6' : isIE7 ? 'IE7' : isIE8 ? 'IE8' : 'IE';
} else if (isGecko){
var isFF = check(/firefox/);
browserType = isFF ? 'Firefox' : 'Others';;
jsType = isGecko2 ? 'Gecko2' : isGecko3 ? 'Gecko3' : 'Gecko';
if(isFF){
var versionStart = ua.indexOf('firefox') + 8;
var versionEnd = ua.indexOf(' ', versionStart);
if(versionEnd == -1){
versionEnd = ua.length;
}
browserVersion = ua.substring(versionStart, versionEnd);
}
} else if(isChrome){
browserType = 'Chrome';
jsType = isWebKit ? 'Web Kit' : 'Other';
var versionStart = ua.indexOf('chrome') + 7;
var versionEnd = ua.indexOf(' ', versionStart);
browserVersion = ua.substring(versionStart, versionEnd);
}else{
browserType = isOpera ? 'Opera' : isSafari ? 'Safari' : '';
}
Here's how to detect browsers in 2016, including Microsoft Edge, Safari 10 and detection of Blink:
// Opera 8.0+ (UA detection to detect Blink/v8-powered Opera)
isOpera = !!window.opera || navigator.userAgent.indexOf(' OPR/') >= 0;
// Firefox 1.0+
isFirefox = typeof InstallTrigger !== 'undefined';
// Safari 3.0+
isSafari = /constructor/i.test(window.HTMLElement) || (function (p) { return p.toString() === "[object SafariRemoteNotification]"; })(!window['safari'] || safari.pushNotification);
// Internet Explorer 6-11
isIE = /*#cc_on!#*/false || !!document.documentMode;
// Edge 20+
isEdge = !isIE && !!window.StyleMedia;
// Chrome 1+
isChrome = !!window.chrome && !!window.chrome.webstore;
// Blink engine detection
isBlink = (isChrome || isOpera) && !!window.CSS;
The beauty of this approach is that it relies on browser engine properties, so it covers even derivative browsers, such as Yandex or Vivaldi, which are practically compatible with the major browsers whose engines they use. The exception is Opera, which relies on user agent sniffing, but today (i.e. ver. 15 and up) even Opera is itself only a shell for Blink.
It is usually best to avoid browser-specific code where possible. The JQuery $.support property is available for detection of support for particular features rather than relying on browser name and version.
In Opera for example, you can fake an internet explorer or firefox instance.
A detailed description of JQuery.support can be found here: http://api.jquery.com/jQuery.support/
Now deprecated according to jQuery.
We strongly recommend the use of an external library such as Modernizr
instead of dependency on properties in jQuery.support.
When coding websites, I always make sure, that basic functionality like navigation is also accessible to non-js users. This may be object to discussion and can be ignored if the homepage is targeted to a special audience.
This tells you all the details about your browser and the version of it.
<!DOCTYPE html>
<html>
<body>
<div id="example"></div>
<script>
txt = "<p>Browser CodeName: " + navigator.appCodeName + "</p>";
txt+= "<p>Browser Name: " + navigator.appName + "</p>";
txt+= "<p>Browser Version: " + navigator.appVersion + "</p>";
txt+= "<p>Cookies Enabled: " + navigator.cookieEnabled + "</p>";
txt+= "<p>Platform: " + navigator.platform + "</p>";
txt+= "<p>User-agent header: " + navigator.userAgent + "</p>";
txt+= "<p>User-agent language: " + navigator.systemLanguage + "</p>";
document.getElementById("example").innerHTML=txt;
</script>
</body>
</html>
All the information about web browser is contained in navigator object. The name and version are there.
var appname = window.navigator.appName;
Source: javascript browser detection
//Copy and paste this into your code/text editor, and try it
//Before you use this to fix compatability bugs, it's best to try inform the browser provider that you have found a bug and there latest browser may not be up to date with the current web standards
//Since none of the browsers use the browser identification system properly you need to do something a bit like this
//Write browser identification
document.write(navigator.userAgent + "<br>")
//Detect browser and write the corresponding name
if (navigator.userAgent.search("MSIE") >= 0){
document.write('"MS Internet Explorer ');
var position = navigator.userAgent.search("MSIE") + 5;
var end = navigator.userAgent.search("; Windows");
var version = navigator.userAgent.substring(position,end);
document.write(version + '"');
}
else if (navigator.userAgent.search("Chrome") >= 0){
document.write('"Google Chrome ');// For some reason in the browser identification Chrome contains the word "Safari" so when detecting for Safari you need to include Not Chrome
var position = navigator.userAgent.search("Chrome") + 7;
var end = navigator.userAgent.search(" Safari");
var version = navigator.userAgent.substring(position,end);
document.write(version + '"');
}
else if (navigator.userAgent.search("Firefox") >= 0){
document.write('"Mozilla Firefox ');
var position = navigator.userAgent.search("Firefox") + 8;
var version = navigator.userAgent.substring(position);
document.write(version + '"');
}
else if (navigator.userAgent.search("Safari") >= 0 && navigator.userAgent.search("Chrome") < 0){//<< Here
document.write('"Apple Safari ');
var position = navigator.userAgent.search("Version") + 8;
var end = navigator.userAgent.search(" Safari");
var version = navigator.userAgent.substring(position,end);
document.write(version + '"');
}
else if (navigator.userAgent.search("Opera") >= 0){
document.write('"Opera ');
var position = navigator.userAgent.search("Version") + 8;
var version = navigator.userAgent.substring(position);
document.write(version + '"');
}
else{
document.write('"Other"');
}
//Use w3schools research the `search()` method as other methods are availible
Since Internet Explorer 11 (IE11+) came out and is not using the tag name of MSIE anymore I came up with a variance of an older detection function:
navigator.sayswho= (function(){
var N= navigator.appName, ua= navigator.userAgent, tem;
// if IE11+
if (new RegExp("Trident/.*rv:([0-9]{1,}[\.0-9]{0,})").exec(ua) !== null) {
var M= ["Internet Explorer"];
if(M && (tem= ua.match(/rv:([0-9]{1,}[\.0-9]{0,})/))!= null) M[2]= tem[1];
M= M? [M[0], M[2]]: [N, navigator.appVersion,'-?'];
return M;
}
var M= ua.match(/(opera|chrome|safari|firefox|msie)\/?\s*(\.?\d+(\.\d+)*)/i);
if(M && (tem= ua.match(/version\/([\.\d]+)/i))!= null) M[2]= tem[1];
M= M? [M[1], M[2]]: [N, navigator.appVersion,'-?'];
return M;
})();
Sadly, IE11 no longer has MSIE in its navigator.userAgent:
Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; OfficeLiveConnector.1.5; OfficeLivePatch.1.3; .NET4.0C; BRI/2; BOIE9;ENUS; rv:11.0) like Gecko
As to why you want to know which browser you're using, it's because every browser has its own set of bugs, and you end up implementing browser and version specific workarounds, or tell the user to use a different browser!
var browser = navigator.appName;
var version = navigator.appVersion;
Note, however, that both will not necessarily reflect the truth. Many browsers can be set to mask as other browsers. So, for example, you can't always be sure if a user is actually surfing with IE6 or with Opera that pretends to be IE6.
This little library may help you. But be aware that browser detection is not always the solution.
Here is how I do custom CSS for Internet Explorer:
In my JavaScript file:
function isIE () {
var myNav = navigator.userAgent.toLowerCase();
return (myNav.indexOf('msie') != -1) ? parseInt(myNav.split('msie')[1]) : false;
}
jQuery(document).ready(function(){
if(var_isIE){
if(var_isIE == 10){
jQuery("html").addClass("ie10");
}
if(var_isIE == 8){
jQuery("html").addClass("ie8");
// you can also call here some function to disable things that
//are not supported in IE, or override browser default styles.
}
}
});
And then in my CSS file, y define each different style:
.ie10 .some-class span{
.......
}
.ie8 .some-class span{
.......
}
Instead of hardcoding web browsers, you can scan the user agent to find the browser name:
navigator.userAgent.split(')').reverse()[0].match(/(?!Gecko|Version|[A-Za-z]+?Web[Kk]it)[A-Z][a-z]+/g)[0]
I've tested this on Safari, Chrome, and Firefox. Let me know if you found this doesn't work on a browser.
Safari: "Safari"
Chrome: "Chrome"
Firefox: "Firefox"
You can even modify this to get the browser version if you want. Do note there are better ways to get the browser version
navigator.userAgent.split(')').reverse()[0].match(/(?!Gecko|Version|[A-Za-z]+?Web[Kk]it)[A-Z][a-z]+\/[\d.]+/g)[0].split('/')
Sample output:
Firefox/39.0
If you want a function that returns the browser as well as the version, here is an improvement from the original answer:
navigator.browserInfo =
(
function()
{
var browser = '';
var version = '';
var idString = '';
var ua = navigator.userAgent;
var tem = [];
var M = ua.match(/(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i);
//IE will be identified as 'Trident' and a different version number. The name must be corrected to 'Internet Explorer' and the correct version identified.
//ie correction
if(/trident/i.test(M[1]))
{
tem = /\brv[ :]+(\d+.?\d*)/g.exec(ua) || [];
browser = 'Internet Explorer';
version = tem[1];
}
//firefox
else if(/firefox/i.test(M[1]))
{
tem = /\brv[ :]+(\d+.?\d*)/g.exec(ua) || [];
browser = 'Firefox';
version = tem[1];
}
//safari
else if(/safari/i.test(M[1]))
{
tem = ua.match(/\bVersion\/(\d+.?\d*\s*\w+)/);
browser = 'Safari';
version = tem[1];
}
//If 'Chrome' is found, it may be another browser.
else if(M[1] === 'Chrome')
{
//opera
var temOpr = ua.match(/\b(OPR)\/(\d+.?\d*.?\d*.?\d*)/);
//edge
var temEdge = ua.match(/\b(Edge)\/(\d+.?\d*)/);
//chrome
var temChrome = ua.match(/\b(Chrome)\/(\d+.?\d*.?\d*.?\d*)/);
//a genuine 'Chrome' reading will result from ONLY temChrome not being null.
var genuineChrome = temOpr == null && temEdge == null && temChrome != null;
if(temOpr != null)
{
browser = temOpr[1].replace('OPR', 'Opera');
version = temOpr[2];
}
if(temEdge != null)
{
browser = temEdge[1];
version = temEdge[2];
}
if(genuineChrome)
{
browser = temChrome[1];
version = temChrome[2];
}
}
//There will be some odd balls, so if you wish to support those browsers, add functionality to display those browsers as well.
if(browser == '' || version == '')
{
idString = 'We couldn\'t find your browser, but you can still use the site';
}
else
{
idString = browser + ' version ' + version;
}
alert('Your browser is ' + idString);
//store the type of browser locally
if(typeof(Storage) !== "undefined")
{
//Store
localStorage.setItem('browser', browser);
localStorage.setItem('version', version);
}
else
{
alert('local storage not available');
}
}
)();
With this, it also stores the result locally, so this check is not necessary to run every time.
This is what I'm using:
var ua = navigator.userAgent;
var info = {
browser: /Edge\/\d+/.test(ua) ? 'ed' : /MSIE 9/.test(ua) ? 'ie9' : /MSIE 10/.test(ua) ? 'ie10' : /MSIE 11/.test(ua) ? 'ie11' : /MSIE\s\d/.test(ua) ? 'ie?' : /rv\:11/.test(ua) ? 'ie11' : /Firefox\W\d/.test(ua) ? 'ff' : /Chrom(e|ium)\W\d|CriOS\W\d/.test(ua) ? 'gc' : /\bSafari\W\d/.test(ua) ? 'sa' : /\bOpera\W\d/.test(ua) ? 'op' : /\bOPR\W\d/i.test(ua) ? 'op' : typeof MSPointerEvent !== 'undefined' ? 'ie?' : '',
os: /Windows NT 10/.test(ua) ? "win10" : /Windows NT 6\.0/.test(ua) ? "winvista" : /Windows NT 6\.1/.test(ua) ? "win7" : /Windows NT 6\.\d/.test(ua) ? "win8" : /Windows NT 5\.1/.test(ua) ? "winxp" : /Windows NT [1-5]\./.test(ua) ? "winnt" : /Mac/.test(ua) ? "mac" : /Linux/.test(ua) ? "linux" : /X11/.test(ua) ? "nix" : "",
touch: 'ontouchstart' in document.documentElement,
mobile: /IEMobile|Windows Phone|Lumia/i.test(ua) ? 'w' : /iPhone|iP[oa]d/.test(ua) ? 'i' : /Android/.test(ua) ? 'a' : /BlackBerry|PlayBook|BB10/.test(ua) ? 'b' : /Mobile Safari/.test(ua) ? 's' : /webOS|Mobile|Tablet|Opera Mini|\bCrMo\/|Opera Mobi/i.test(ua) ? 1 : 0,
tablet: /Tablet|iPad/i.test(ua),
};
info properties:
browser: gc for Google Chrome; ie9-ie11 for IE; ie? for old or unknown IE; ed for Edge; ff for Firefox; sa for Safari; op for Opera.
os: mac win7 win8 win10 winnt winxp winvista linux nix
mobile: a for Android; i for iOS (iPhone iPad); w for Windows Phone; b for Blackberry; s for undetected mobile running Safari; 1 for other undetected mobile; 0 for non-mobile
touch: true for touch enabled devices, including touch laptops/notebooks that has both mouse and touch together; false for no touch support
tablet: true or false
https://jsfiddle.net/oriadam/ncb4n882/
You could use the jQuery library to detect the browser version.
Example:
jQuery.browser.version
However, this only makes sense if you are also using other functions of jQuery. Adding an entire library just to detect the browser seems like overkill to me.
More information:
http://api.jquery.com/jQuery.browser/
(you have to scroll down a bit)
var isOpera = !!window.opera || navigator.userAgent.indexOf('Opera') >= 0;
// Opera 8.0+ (UA detection to detect Blink/v8-powered Opera)
var isFirefox = typeof InstallTrigger !== 'undefined'; // Firefox 1.0+
var isSafari = Object.prototype.toString.call(window.HTMLElement).indexOf('Constructor') > 0;
// At least Safari 3+: "[object HTMLElementConstructor]"
var isChrome = !!window.chrome; // Chrome 1+
var isIE = /*#cc_on!#*/false;
you can more read
How to detect Safari, Chrome, IE, Firefox and Opera browser?
I know I'm WAY late to this question, but figured I'd throw my snippets up here. A lot of the answers here are OK, and, as one points out, it's generally best to use feature detection rather than rely on the userAgent string. However, if you are going to go that route, I've written a complete snippet, as well as an alternate jQuery implementation to replace the depricated $.browser.
Vanilla JS
My first snippet simply adds four properties to the navigator object: browser, version, mobile, & webkit.
jsFiddle
GitHub
min
/** navigator [extended]
* Simply extends Browsers navigator Object to include browser name, version number, and mobile type (if available).
*
* #property {String} browser The name of the browser.
* #property {Double} version The current Browser version number.
* #property {String|Boolean} mobile Will be `false` if is not found to be mobile device. Else, will be best guess Name of Mobile Device (not to be confused with browser name)
* #property {Boolean} webkit If is webkit or not.
*/
;(function(){function c(){try{switch(!0){case /MSIE|Trident/i.test(navigator.userAgent):return"MSIE";case /Chrome/.test(navigator.userAgent):return"Chrome";case /Opera/.test(navigator.userAgent):return"Opera";case /Kindle|Silk|KFTT|KFOT|KFJWA|KFJWI|KFSOWI|KFTHWA|KFTHWI|KFAPWA|KFAPWI/i.test(navigator.userAgent):return/Silk/i.test(navigator.userAgent)?"Silk":"Kindle";case /BlackBerry/.test(navigator.userAgent):return"BlackBerry";case /PlayBook/.test(navigator.userAgent):return"PlayBook";case /BB[0-9]{1,}; Touch/.test(navigator.userAgent):return"Blackberry";
case /Android/.test(navigator.userAgent):return"Android";case /Safari/.test(navigator.userAgent):return"Safari";case /Firefox/.test(navigator.userAgent):return"Mozilla";case /Nokia/.test(navigator.userAgent):return"Nokia"}}catch(a){console.debug("ERROR:setBrowser\t",a)}}function d(){try{switch(!0){case /Sony[^ ]*/i.test(navigator.userAgent):return"Sony";case /RIM Tablet/i.test(navigator.userAgent):return"RIM Tablet";case /BlackBerry/i.test(navigator.userAgent):return"BlackBerry";case /iPhone/i.test(navigator.userAgent):return"iPhone";
case /iPad/i.test(navigator.userAgent):return"iPad";case /iPod/i.test(navigator.userAgent):return"iPod";case /Opera Mini/i.test(navigator.userAgent):return"Opera Mini";case /IEMobile/i.test(navigator.userAgent):return"IEMobile";case /BB[0-9]{1,}; Touch/i.test(navigator.userAgent):return"BlackBerry";case /Nokia/i.test(navigator.userAgent):return"Nokia";case /Android/i.test(navigator.userAgent):return"Android"}}catch(a){console.debug("ERROR:setMobile\t",a)}return!1}function e(){try{switch(!0){case /MSIE|Trident/i.test(navigator.userAgent):return/Trident/i.test(navigator.userAgent)&&
/rv:([0-9]{1,}[\.0-9]{0,})/.test(navigator.userAgent)?parseFloat(navigator.userAgent.match(/rv:([0-9]{1,}[\.0-9]{0,})/)[1].replace(/[^0-9\.]/g,"")):/MSIE/i.test(navigator.userAgent)&&0<parseFloat(navigator.userAgent.split("MSIE")[1].replace(/[^0-9\.]/g,""))?parseFloat(navigator.userAgent.split("MSIE")[1].replace(/[^0-9\.]/g,"")):"Edge";case /Chrome/.test(navigator.userAgent):return parseFloat(navigator.userAgent.split("Chrome/")[1].split("Safari")[0].replace(/[^0-9\.]/g,""));case /Opera/.test(navigator.userAgent):return parseFloat(navigator.userAgent.split("Version/")[1].replace(/[^0-9\.]/g,
""));case /Kindle|Silk|KFTT|KFOT|KFJWA|KFJWI|KFSOWI|KFTHWA|KFTHWI|KFAPWA|KFAPWI/i.test(navigator.userAgent):if(/Silk/i.test(navigator.userAgent))return parseFloat(navigator.userAgent.split("Silk/")[1].split("Safari")[0].replace(/[^0-9\.]/g,""));if(/Kindle/i.test(navigator.userAgent)&&/Version/i.test(navigator.userAgent))return parseFloat(navigator.userAgent.split("Version/")[1].split("Safari")[0].replace(/[^0-9\.]/g,""));case /BlackBerry/.test(navigator.userAgent):return parseFloat(navigator.userAgent.split("/")[1].replace(/[^0-9\.]/g,
""));case /PlayBook/.test(navigator.userAgent):case /BB[0-9]{1,}; Touch/.test(navigator.userAgent):case /Safari/.test(navigator.userAgent):return parseFloat(navigator.userAgent.split("Version/")[1].split("Safari")[0].replace(/[^0-9\.]/g,""));case /Firefox/.test(navigator.userAgent):return parseFloat(navigator.userAgent.split(/Firefox\//i)[1].replace(/[^0-9\.]/g,""));case /Android/.test(navigator.userAgent):return parseFloat(navigator.userAgent.split("Version/")[1].split("Safari")[0].replace(/[^0-9\.]/g,
""));case /Nokia/.test(navigator.userAgent):return parseFloat(navigator.userAgent.split("Browser")[1].replace(/[^0-9\.]/g,""))}}catch(a){console.debug("ERROR:setVersion\t",a)}}a:{try{if(navigator&&navigator.userAgent){navigator.browser=c();navigator.mobile=d();navigator.version=e();var b;b:{try{b=/WebKit/i.test(navigator.userAgent);break b}catch(a){console.debug("ERROR:setWebkit\t",a)}b=void 0}navigator.webkit=b;break a}}catch(a){}throw Error("Browser does not support `navigator` Object |OR| has undefined `userAgent` property.");
}})();
/* simple c & p of above */
var isOpera = !!window.opera || navigator.userAgent.indexOf(' OPR/') >= 0;
// Opera 8.0+ (UA detection to detect Blink/v8-powered Opera)
var isFirefox = typeof InstallTrigger !== 'undefined'; // Firefox 1.0+
var isSafari = Object.prototype.toString.call(window.HTMLElement).indexOf('Constructor') > 0;
// At least Safari 3+: "[object HTMLElementConstructor]"
var isChrome = !!window.chrome && !isOpera; // Chrome 1+
var isIE = /*#cc_on!#*/false || !!document.documentMode;
// Edge 20+
var isEdge = !isIE && !!window.StyleMedia;
// Chrome 1+
var output = 'Detecting browsers by ducktyping:<hr>';
output += 'isFirefox: ' + isFirefox + '<br>';
output += 'isChrome: ' + isChrome + '<br>';
output += 'isSafari: ' + isSafari + '<br>';
output += 'isOpera: ' + isOpera + '<br>';
output += 'isIE: ' + isIE + '<br>';
output += 'isIE Edge: ' + isEdge + '<br>';
document.body.innerHTML = output;
Not exactly what you want, but close to it:
var jscriptVersion = /*#cc_on #if(#_jscript) #_jscript_version #else #*/ false /*#end #*/;
var geckoVersion = navigator.product === 'Gecko' && navigator.productSub;
var operaVersion = 'opera' in window && 'version' in opera && opera.version();
The variables will contain the appropriate version or false if it is not available.
I'd appreciate it if someone using Chrome could find out if you can use window.chrome in a similar way to window.opera.
Some times we need simple method to check if the browser is IE or not. This is how it could be:
var isMSIE = (/trident/i).test(navigator.userAgent);
if(isMSIE)
{
/* do something for ie */
}
else
{
/* do something else */
}
or simplified siva's method:
if(!!navigator.systemLanguage)
{
/* do something for ie */
}
else
{
/* do something else */
}
MSIE v.11 check:
if( (/trident/i).test(navigator.userAgent) && (/rv:/i).test(navigator.userAgent) )
{
/* do something for ie 11 */
}
other IE browsers contain MSIE string in their userAgent property and could be catched by it.
I found something interesting and quicker way.
IE supports navigator.systemLanguage which returns "en-US" where other browsers return undefined.
<script>
var lang = navigator.systemLanguage;
if (lang!='en-US'){document.write("Well, this is not internet explorer");}
else{document.write("This is internet explorer");}
</script>
I make this small function, hope it helps. Here you can find the latest version
browserDetection
function detectBrowser(userAgent){
var chrome = /.*(Chrome\/).*(Safari\/).*/g;
var firefox = /.*(Firefox\/).*/g;
var safari = /.*(Version\/).*(Safari\/).*/g;
var opera = /.*(Chrome\/).*(Safari\/).*(OPR\/).*/g
if(opera.exec(userAgent))
return "Opera"
if(chrome.exec(userAgent))
return "Chrome"
if(safari.exec(userAgent))
return "Safari"
if(firefox.exec(userAgent))
return "Firefox"
}
Below code snippet will show how how you can show UI elemnts depends on IE version and browser
$(document).ready(function () {
var msiVersion = GetMSIieversion();
if ((msiVersion <= 8) && (msiVersion != false)) {
//Show UI elements specific to IE version 8 or low
} else {
//Show UI elements specific to IE version greater than 8 and for other browser other than IE,,ie..Chrome,Mozila..etc
}
}
);
Below code will give how we can get IE version
function GetMSIieversion() {
var ua = window.navigator.userAgent;
var msie = ua.indexOf('MSIE ');
if (msie > 0) {
// IE 10 or older => return version number
return parseInt(ua.substring(msie + 5, ua.indexOf('.', msie)), 10);
}
var trident = ua.indexOf('Trident/');
if (trident > 0) {
// IE 11 => return version number
var rv = ua.indexOf('rv:');
return parseInt(ua.substring(rv + 3, ua.indexOf('.', rv)), 10);
}
var edge = ua.indexOf('Edge/');
if (edge > 0) {
// Edge (IE 12+) => return version number
return parseInt(ua.substring(edge + 5, ua.indexOf('.', edge)), 10);
}
// other browser like Chrome,Mozila..etc
return false;
}

Categories

Resources