How to detect unpopular browsers (baidu) using JavaScript? - javascript

I'm trying to make my app cross-browser by providing two styles, one for browsers that support CSS 3d animation, and one for the browsers that don't, using this code to feature-detect:
// Function from: https://stackoverflow.com/a/36191841/7982963
const isValueSupported = (prop, value) => {
const el = document.createElement('div');
el.style[prop] = value;
return el.style[prop] === value;
}
// [unction from: http://lea.verou.me/2009/02/check-if-a-css-property-is-supported/
const isPropertySupported = property => property in document.body.style;
// Detection style inspired by Modernizr library
if (isValueSupported('perspective', '400px') && isValueSupported('transform-style', 'preserve-3d') && isValueSupported('backface-visibility', 'hidden') && isValueSupported('transform', 'rotateY(-180deg)') && isPropertySupported('perspective') && isPropertySupported('transform-style') && isPropertySupported('backface-visibility') && isPropertySupported('transform') && (!navigator.userAgent.includes('Firefox'))) {
document.documentElement.classList.add('csstransforms3d');
} else {
document.documentElement.classList.add('no-csstransforms3d');
}
The problem is that, although some browsers, like Firefox, pass the test, they have some known bugs like Mozilla's backface-visibility bug, so I had to browser-sniff :(.
I quickly found useful results for Firefox: if (navigator.userAgent.includes('Firefox')), but for another browser it happens that I have on my computer called "Baidu browser", I couldn't find any results.
So how to detect these kinds of browsers?

You can detect popular browsers in JavaScript with the following code.
// Mobile Browsers
export const isMobile = () => {
const ua = (navigator || {}).userAgent;
if (ua) {
return (/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini|Mobile|mobile|CriOS/i.test(ua))
}
return false;
}
// Opera 8.0+
export const isOpera = () => {
let opr = window.opr || {};
return (!!window.opr && !!opr.addons) || !!window.opera || navigator.userAgent.indexOf(' OPR/') >= 0;
}
// Firefox 1.0+
export const isFirefox = () => typeof InstallTrigger !== 'undefined';
// Safari 3.0+ "[object HTMLElementConstructor]"
export const isSafari = () => {
let safari = window.safari || {};
return /constructor/i.test(window.HTMLElement) || (function (p) { return p.toString() === "[object SafariRemoteNotification]"; })(!window['safari'] || (typeof safari !== 'undefined' && safari.pushNotification));
}
// Internet Explorer 6-11
export const isIE = () => /*#cc_on!#*/false || !!document.documentMode;
// Edge 20+
export const isEdge = () => !isIE() && !!window.StyleMedia;
// Chrome 1+
export const isChrome = () => !!window.chrome && !!window.chrome.loadTimes;
So anything that doesn't match any of these popular browsers, will be an unpopular browser.

Related

Why is JavaScript treating windows 10 pro, IE11 as mobile or tablet?

I do not have mobile / tablet compatible layout, so when any user comes from mobile/tablet/linux terminal, I show a page "get out". But if the user is coming from a PC browsers IE old, IE edge, Safari, Google Chrome, Firefox, Opera, Midori etc etc. Then it is allowed.
Why am I getting is_pc as false even the browser was PC and IE11?
window.onload = userAgentDetect;
var is_pc = true;
function userAgentDetect() {
if(window.navigator.userAgent.match(/Mobile/i)
|| window.navigator.userAgent.match(/iPhone/i)
|| window.navigator.userAgent.match(/iPod/i)
|| window.navigator.userAgent.match(/IEMobile/i)
|| window.navigator.userAgent.match(/Windows Phone/i)
|| window.navigator.userAgent.match(/Android/i)
|| window.navigator.userAgent.match(/BlackBerry/i)
|| window.navigator.userAgent.match(/webOS/i)) {
document.body.className+=' mobile';
is_pc = false;
get_out_from_here();
}
if(window.navigator.userAgent.match(/Tablet/i)
|| window.navigator.userAgent.match(/iPad/i)
|| window.navigator.userAgent.match(/Nexus 7/i)
|| window.navigator.userAgent.match(/Nexus 10/i)
|| window.navigator.userAgent.match(/KFAPWI/i)) {
document.body.className-=' mobile';
document.body.className+=' tablet';
is_pc = false;
get_out_from_here();
}
}
Working.
window.onload = userAgentDetect;
var is_pc = true;
function userAgentDetect() {
if(window.navigator.userAgent.match(/Mobile/i)
|| window.navigator.userAgent.match(/iPhone/i)
|| window.navigator.userAgent.match(/iPod/i)
|| window.navigator.userAgent.match(/IEMobile/i)
|| window.navigator.userAgent.match(/Windows Phone/i)
|| window.navigator.userAgent.match(/Android/i)
|| window.navigator.userAgent.match(/BlackBerry/i)
|| window.navigator.userAgent.match(/webOS/i)) {
document.body.className+=' mobile';
is_pc = false;
get_out_from_here();
}
if(window.navigator.userAgent.match(/iPad/i)
|| window.navigator.userAgent.match(/Nexus 7/i)
|| window.navigator.userAgent.match(/Nexus 10/i)
|| window.navigator.userAgent.match(/KFAPWI/i)) {
document.body.className-=' mobile';
document.body.className+=' tablet';
is_pc = false;
get_out_from_here();
}
}

How to detect Acrobat X Pro installed on machine using javascript

How can I detect if Acrobat X Pro is installed on a machine using javascript. I have code that works for Adobe Reader. but now I have upgrdaed my adobe version to Acrobat X Pro. But it is not working for Acrobat X Pro using IE8.
var perform_acrobat_detection = function()
{
//
// The returned object
//
var browser_info = {
name: null,
acrobat : null,
acrobat_ver : null
};
if(navigator && (navigator.userAgent.toLowerCase()).indexOf("chrome") > -1)
browser_info.name = "chrome";
else if(navigator && (navigator.userAgent.toLowerCase()).indexOf("msie") > -1)
browser_info.name = "ie";
else if(navigator && (navigator.userAgent.toLowerCase()).indexOf("firefox") > -1)
browser_info.name = "firefox";
else if(navigator && (navigator.userAgent.toLowerCase()).indexOf("msie") > -1)
browser_info.name = "other";
try {
if(browser_info.name == "ie") {
var control = null;
//
// load the activeX control
//
try {
// AcroPDF.PDF is used by version 7 and later
control = new ActiveXObject('AcroPDF.PDF');
}
catch (e){}
if (!control) {
try {
// PDF.PdfCtrl is used by version 6 and earlier
control = new ActiveXObject('PDF.PdfCtrl');
}
catch (e) {}
}
if(!control) {
browser_info.acrobat == null;
return browser_info;
}
version = control.GetVersions().split(',');
version = version[0].split('=');
browser_info.acrobat = "installed";
browser_info.acrobat_ver = parseFloat(version[1]);
}
else if(browser_info.name == "chrome") {
for(key in navigator.plugins)
{
if(navigator.plugins[key].name == "Chrome PDF Viewer" || navigator.plugins[key].name == "Adobe Acrobat") {
browser_info.acrobat = "installed";
browser_info.acrobat_ver = parseInt(navigator.plugins[key].version) || "Chome PDF Viewer";
}
}
}
//
// NS3+, Opera3+, IE5+ Mac, Safari (support plugin array): check for Acrobat plugin in plugin array
//
else if(navigator.plugins != null)
{
var acrobat = navigator.plugins['Adobe Acrobat'];
if(acrobat == null)
{
browser_info.acrobat = null;
return browser_info;
}
browser_info.acrobat = "installed";
browser_info.acrobat_ver = parseInt(acrobat.version[0]);
}
}
catch(e)
{
browser_info.acrobat_ver = null;
}
return browser_info;
};
var browser_info = perform_acrobat_detection();

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";
}

Detect Safari using jQuery

Though both are Webkit based browsers, Safari urlencodes quotation marks in the URL while Chrome does not.
Therefore I need to distinguish between these two in JS.
jQuery's browser detection docs mark "safari" as deprecated.
Is there a better method or do I just stick with the deprecated value for now?
Using a mix of feature detection and Useragent string:
var is_opera = !!window.opera || navigator.userAgent.indexOf(' OPR/') >= 0;
var is_Edge = navigator.userAgent.indexOf("Edge") > -1;
var is_chrome = !!window.chrome && !is_opera && !is_Edge;
var is_explorer= typeof document !== 'undefined' && !!document.documentMode && !is_Edge;
var is_firefox = typeof window.InstallTrigger !== 'undefined';
var is_safari = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
Usage:
if (is_safari) alert('Safari');
Or for Safari only, use this :
if ( /^((?!chrome|android).)*safari/i.test(navigator.userAgent)) {alert('Its Safari');}
The following identifies Safari 3.0+ and distinguishes it from Chrome:
isSafari = !!navigator.userAgent.match(/Version\/[\d\.]+.*Safari/)
unfortunately the above examples will also detect android's default browser as Safari, which it is not.
I used
navigator.userAgent.indexOf('Safari') != -1 && navigator.userAgent.indexOf('Chrome') == -1 && navigator.userAgent.indexOf('Android') == -1
For checking Safari I used this:
$.browser.safari = ($.browser.webkit && !(/chrome/.test(navigator.userAgent.toLowerCase())));
if ($.browser.safari) {
alert('this is safari');
}
It works correctly.
Apparently the only reliable and accepted solution would be to do feature detection like this:
browser_treats_urls_like_safari_does = false;
var last_location_hash = location.hash;
location.hash = '"blah"';
if (location.hash == '#%22blah%22')
browser_treats_urls_like_safari_does = true;
location.hash = last_location_hash;
The only way I found is check if navigator.userAgent contains iPhone or iPad word
if (navigator.userAgent.toLowerCase().match(/(ipad|iphone)/)) {
//is safari
}
If you are checking the browser use $.browser. But if you are checking feature support (recommended) then use $.support.
You should NOT use $.browser to enable/disable features on the page. Reason being its not dependable and generally just not recommended.
If you need feature support then I recommend modernizr.
//Check if Safari
function isSafari() {
return /^((?!chrome).)*safari/i.test(navigator.userAgent);
}
//Check if MAC
if(navigator.userAgent.indexOf('Mac')>1){
alert(isSafari());
}
http://jsfiddle.net/s1o943gb/10/
This will determine whether the browser is Safari or not.
if(navigator.userAgent.indexOf('Safari') !=-1 && navigator.userAgent.indexOf('Chrome') == -1)
{
alert(its safari);
}else {
alert('its not safari');
}
I use to detect Apple browser engine, this simple JavaScript condition:
navigator.vendor.startsWith('Apple')
A very useful way to fix this is to detect the browsers webkit version and check if it is at least the one we need, else do something else.
Using jQuery it goes like this:
"use strict";
$(document).ready(function() {
var appVersion = navigator.appVersion;
var webkitVersion_positionStart = appVersion.indexOf("AppleWebKit/") + 12;
var webkitVersion_positionEnd = webkitVersion_positionStart + 3;
var webkitVersion = appVersion.slice(webkitVersion_positionStart, webkitVersion_positionEnd);
console.log(webkitVersion);
if (webkitVersion < 537) {
console.log("webkit outdated.");
} else {
console.log("webkit ok.");
};
});
This provides a safe and permanent fix for dealing with problems with browser's different webkit implementations.
Happy coding!
// Safari uses pre-calculated pixels, so use this feature to detect Safari
var canva = document.createElement('canvas');
var ctx = canva.getContext("2d");
var img = ctx.getImageData(0, 0, 1, 1);
var pix = img.data; // byte array, rgba
var isSafari = (pix[3] != 0); // alpha in Safari is not zero
Generic FUNCTION
var getBrowseActive = function (browserName) {
return navigator.userAgent.indexOf(browserName) > -1;
};
My best solution
function getBrowserInfo() {
const ua = navigator.userAgent; let tem;
let 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(/\bOPR\/(\d+)/);
if (tem != null) {
return { name: 'Opera', version: tem[1] };
}
}
M = M[2] ? [M[1], M[2]] : [navigator.appName, navigator.appVersion, '-?'];
tem = ua.match(/version\/(\d+)/i);
if (tem != null) {
M.splice(1, 1, tem[1]);
}
return {
name: M[0],
version: M[1],
};
}
getBrowserInfo();

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