Reference »

How to detect browser version in JavaScript

let browserName  = navigator.appName;
let fullVersion  = `${parseFloat(navigator.appVersion)}`;
let nameOffset, verOffset, ix;

//	In Opera, the true version is after "OPR" or after "Version"
if ((verOffset = navigator.userAgent.indexOf("OPR")) != -1) {
	browserName = "Opera";
	fullVersion = navigator.userAgent.slice(verOffset + 4);
	if ((verOffset = navigator.userAgent.indexOf("Version")) != -1) 
		fullVersion = navigator.userAgent.slice(verOffset + 8);
}
//	In MS Edge, the true version is after "Edg" in userAgent
else if ((verOffset = navigator.userAgent.indexOf("Edg")) != -1) {
	browserName = "Microsoft Edge";
	fullVersion = navigator.userAgent.slice(verOffset + 4);
}
//	In MSIE, the true version is after "MSIE" in userAgent
else if ((verOffset = navigator.userAgent.indexOf("MSIE")) != -1) {
	browserName = "Microsoft Internet Explorer";
	fullVersion = navigator.userAgent.slice(verOffset + 5);
}
//	In Chrome, the true version is after "Chrome" 
else if ((verOffset = navigator.userAgent.indexOf("Chrome")) != -1) {
	browserName = "Chrome";
	fullVersion = navigator.userAgent.slice(verOffset + 7);
}
//	In Safari, the true version is after "Safari" or after "Version" 
else if ((verOffset = navigator.userAgent.indexOf("Safari")) != -1) {
	browserName = "Safari";
	fullVersion = navigator.userAgent.slice(verOffset + 7);
	if ((verOffset = navigator.userAgent.indexOf("Version")) != -1) 
		fullVersion = navigator.userAgent.slice(verOffset + 8);
}
//	In Firefox, the true version is after "Firefox" 
else if ((verOffset = navigator.userAgent.indexOf("Firefox")) != -1) {
	browserName = "Firefox";
	fullVersion = navigator.userAgent.slice(verOffset + 8);
}
//	In most other browsers, "name/version" is at the end of userAgent 
else if (  (nameOffset = navigator.userAgent.lastIndexOf(' ') + 1) 
		 < (verOffset  = navigator.userAgent.lastIndexOf('/')    ) ) {
	browserName = navigator.userAgent.slice(nameOffset,verOffset);
	fullVersion = navigator.userAgent.slice(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.slice(0, ix);
if ((ix = fullVersion.indexOf(" ")) != -1)
	fullVersion = fullVersion.slice(0, ix);

console.log(`${browserName} ${fullVersion}`);