Christian Eric Paran
Christian Eric Paran

Reputation: 1010

How can I determine what browser is being used with JavaScript?

I have a problem in determining browsers.

I've tried using navigator and well, it did not help.

I used alert(navigator.appName); to determine the browser and I'm currently using Google Chrome, when the pop up appears it displayed Mozilla, but in Mozilla it works fine and with Mozilla itself.

Is there a problem with the code, or is it a bug?

Upvotes: 7

Views: 26288

Answers (7)

empire1138
empire1138

Reputation: 11

Here's a really good article that should answer all your questions.

Upvotes: 0

Robert Paul Raise
Robert Paul Raise

Reputation: 1

navigator.userAgentData.brands[0].brand

This will give you the browser name.

Upvotes: 0

JakeParis
JakeParis

Reputation: 11210

To answer your question, no there is no problem or bug. Chrome represents itself as Mozilla. See this for the exact User Agent strings which Chrome gives.

http://www.useragentstring.com/pages/useragentstring.php?name=Chrome

Here are some examples:

Chrome 20.0.1092.0

Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/536.6 (KHTML, like Gecko) Chrome/20.0.1092.0 Safari/536.6

Chrome 20.0.1090.0

Mozilla/5.0 (Windows NT 6.2) AppleWebKit/536.6 (KHTML, like Gecko) Chrome/20.0.1090.0 Safari/536.6

Upvotes: 2

Bakudan
Bakudan

Reputation: 19492

The browser sniffing wikipedia MDC is not considered a good practice. What if there is new browser, not publically available? The detection should be towards features not browsers. Browsers may change, became outdated, features are persistent.

Just for the of completeness and the spirit of adventure - there is a way to test for specific JavaScript object:

isChrome = function() { return !!(window.chrome);}
isOpera = function() { return !!(window.opera);}

For IE there is this magic thingy called conditional compilation SO Question and materials about it MSDN JSkit.

Upvotes: 0

Lyn Headley
Lyn Headley

Reputation: 11588

Try navigator.appVersion, it should be more specific.

Upvotes: 0

kennebec
kennebec

Reputation: 104780

navigator.sayswho= (function(){
    var N= navigator.appName, ua= navigator.userAgent, tem,
    M= ua.match(/(opera|chrome|safari|firefox|msie)\/?\s*([\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.join(' ');
})();

alert(navigator.sayswho)

Upvotes: 6

Alexander Blacks
Alexander Blacks

Reputation: 61

It's close to chrome, if you need a simple short solution try to use this:

function getBrowser() {
  if( navigator.userAgent.indexOf("Chrome") != -1 ) {
    return "Chrome";
  } else if( navigator.userAgent.indexOf("Opera") != -1 ) {
    return "Opera";
  } else if( navigator.userAgent.indexOf("MSIE") != -1 ) {
    return "IE";
  } else if( navigator.userAgent.indexOf("Firefox") != -1 ) {
    return "Firefox";
  } else {
    return "unknown";
  }
}

Upvotes: 5

Related Questions