52
if(firefox and is on a computer){
alert('using firefox on a computer')
}else{
alert("using something else!");
}

How can I do this?

TIMEX
  • 259,804
  • 351
  • 777
  • 1,080
  • 4
    What does "is on a computer mean" ? Do you want to also detect iphones and other mobile deveices ? – mP. Feb 24 '10 at 09:44
  • 1
    Why do you want to know that? – Gumbo Feb 24 '10 at 10:01
  • 3
    because the q says if firefox AND is on a computer ? The is on a computer must be important otherwise it wouldnt be there.. after all its redundant otherwise. – mP. Feb 24 '10 at 12:40
  • Note that Firefox on iOS uses WebKit rather than Gecko rendering engine due to a policy enforced by Apple on iOS apps. You have to keep in mind, if you want to detect the brand name of the browser, or the rendering engine. – 1j01 Jul 08 '21 at 16:03

13 Answers13

57

What you're after is known as browser detection:

if ($.browser.mozilla) { ... 

However, browser sniffing is discouraged, as its easy to spoof the user agent, i.e. pretend to be another browser!

You'd best use feature detection, either in your own way, or through the jQuery.support interface: http://api.jquery.com/jQuery.support/

Here's an article on extending it for your own use: http://www.waytoocrowded.com/2009/03/14/jquery-supportminheight/

Edit:

Found this post as well which helps: When IE8 is not IE8 what is $.browser.version?

Community
  • 1
  • 1
James Wiseman
  • 29,946
  • 17
  • 95
  • 158
  • 2
    You mean discouraged? ;) +1 for feature detection, please do it 'the right way': http://www.nczonline.net/blog/2009/12/29/feature-detection-is-not-browser-detection/ – Marcel Korpel Feb 24 '10 at 10:05
  • @Marcel Korpel: Brilliant article, by the way. I realised that I didn't properly understand feature detection. Have you posted that in an answer? Because I'd happily vote it up! – James Wiseman Feb 24 '10 at 10:40
  • 2
    I don't agree with your "the right way". Spoofing the user agent is not done for evil purpose, but to workaround developer bugs. So it's better trust what user wants you think he is.. he has better reason than you – Jack Jan 12 '16 at 12:29
  • Sometimes you will still need to find out what the agent is and make a best guess. I'm pretty sure (not 100%!) that I can detect if Java plugin is already installed and enabled, but there is no JavaScript "feature" that can report if it's even possible. I know that Java is supported in Firefox for a tiny bit longer (not much!), so I have to use sniffing. That is just an example, though-- you can imagine that other technologies will be platform-dependent yet not exposed as a JavaScript feature. +1 to this answer for me. – Greg Pettit Oct 03 '16 at 18:00
  • 10
    This is depreciated and removed from the latest jQuery – dukevin Dec 03 '16 at 15:00
  • 3
    It outputs: "TypeError: $.browser is undefined", because this property was removed from latest versions of jQuery. – Oleksii Kyslytsyn Sep 16 '17 at 18:04
45

I am doing some thing like below;

function checkBrowser(){
    let browser = "";
    let c = navigator.userAgent.search("Chrome");
    let f = navigator.userAgent.search("Firefox");
    let m8 = navigator.userAgent.search("MSIE 8.0");
    let m9 = navigator.userAgent.search("MSIE 9.0");
    if (c > -1) {
        browser = "Chrome";
    } else if (f > -1) {
        browser = "Firefox";
    } else if (m9 > -1) {
        browser ="MSIE 9.0";
    } else if (m8 > -1) {
        browser ="MSIE 8.0";
    }
    return browser;
}
Fayyaz Ali
  • 787
  • 1
  • 8
  • 18
  • You're introducing global variables, and this does not look like a robust way to check this. For instance, this detects Edge as "Chrome" – 1j01 Sep 17 '19 at 22:31
  • Please have a look at the date of my answer, let was introduced later. – Fayyaz Ali Nov 25 '20 at 05:04
  • You don't need `let` to avoid global variables, you can use `var`, since the beginning of JavaScript's history. – 1j01 Nov 25 '20 at 17:12
  • @1j01 Yeah, you are right, please share a proposed better version – Fayyaz Ali Jul 06 '21 at 16:10
  • Well the global leaks are fixed now, but I don't know what the best version of browser detection is; it would need a lot of data and browser testing. And really, you need to keep in mind what the goal is, for instance, if you want to display the name of the browser someone's using (there are hundreds!), or to to target a specific rendering engine to avoid a bug (there are only a few). – 1j01 Jul 08 '21 at 15:56
16

Like this: Check for Firefox. Or some other browser.

 window.onload = function() {
          //  alert(navigator.userAgent);
            if (navigator.userAgent.indexOf("Firefox") > 0) {
                alert("ff");
            }
        }
poo
  • 1,095
  • 4
  • 13
  • 21
14
if (navigator.userAgent.indexOf("Firefox") != -1) {

 //some specific code for Mozilla

 }
David Castro
  • 1,773
  • 21
  • 21
4

It's better to detect features you need, not a browser. For example, if you need to know if foo() is supported, you can check it with if(foo){}

Sam Dark
  • 5,291
  • 1
  • 34
  • 52
4
navigator.sayswho= (function(){
  var N= navigator.appName, ua= navigator.userAgent, tem;
  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.join(' ');
 })();

as the name suggests, this is who the browser says it is- but use object detection before asking it to actually do anything...

I use it for logging errors from users and in testing code in multiple browsers- where I know the userAgent strings.

kennebec
  • 102,654
  • 32
  • 106
  • 127
3

For a quick and dirty solution just do the following, it is cleaner to use includes() when you are searching the 'Firefox' keyword in the NavigatorID.userAgent property than indexOf().

const isFirefoxBrowser = navigator.userAgent.includes('Firefox');

WARNING:

Browser identification based on detecting the user agent string is unreliable and is not recommended, as the user agent string is user configurable.

Read more about userAgent on MDN >>

RECOMMENDED SOLUTION:

Use feature detection instead of browser detection.

Feature detection involves working out whether a browser supports a certain block of code, and running different code dependent on whether it does (or doesn't), so that the browser can always provide a working experience rather crashing/erroring in some browsers.

Read more about implementing feature detection on MDN >>

webpreneur
  • 795
  • 9
  • 15
  • 1
    While this code may answer the question but adding an explanation of the code would be helpful to future readers. – Boken Mar 29 '19 at 09:36
1

http://api.jquery.com/jQuery.browser/

if ($.browser.mozilla) { ...
Franco
  • 905
  • 1
  • 7
  • 16
1

You can make the control with javascript's navigator.userAgent or navigator object in general,

But if you want to use something ready to go, check this:

http://www.quirksmode.org/js/detect.html

hope this helps, Sinan.

Sinan
  • 11,443
  • 7
  • 37
  • 48
1

As already asked in a comment: why do you want this? Browser sniffing is a bad habit and there are only a few situations where it is needed.

Instead, use feature detection. As described by Nicholas Zakas, you should test relatively 'uncommon' features before using them and only rely on these tests, so you're kind of fail-safe. For example, do

if (window.XMLHttpRequest)
    var xhr = new XMLHttpRequest();

instead of

if ((brwsr.IE && brwsr.IE.version >= 7) || (brwsr.firefox) || (brwsr.opera))
    var xhr = new XMLHttpRequest();

And also don't do

if (window.XMLHttpRequest)
    // Hey, native XMLHttpRequest-support, so position: fixed is also supported

(instead, test if position: fixed is supported)

There exist several uncommon browsers with names like Kazehakase and Midori that also might, or might not, support these features, so your scripts will silently work on them when using feature detection.

But please read the mentioned article, as it contains a very good and thorough explanation of this technique. (By the way, I think that Zakas' Professional JavaScript for Web Developers is still too unknown.)

Marcel Korpel
  • 21,536
  • 6
  • 60
  • 80
  • 3
    It'd be nice if this always worked. But sometimes you have a case where features are implemented slightly differently in different browsers, but this difference isn't declared in a variable. For instance, I'm trying to deal with the problem that you can't copy text from disabled fields in firefox, but you can in every other browser. So I need to switch to using the readOnly attribute in firefox. There's no way to detect this other than knowing the user agent. – jsarma Nov 28 '13 at 02:39
1
typeof InstallTrigger !== 'undefined'

It's simple and works well after Quantum but not sure whether this will be future-proof though: https://developer.mozilla.org/en-US/docs/Web/API/InstallTrigger

goodhyun
  • 4,814
  • 3
  • 33
  • 25
0

Any solutions that are mentioned here are not safe because the agent does not always provide the correct browser name in the first place. If you call a page with chrome you also have safari in the agent. That means if safari is the first thing to happen with an if query then you have safari on elseif you have no elseif and only if then the override is overridden in this case safari. This solution is not the safest but it always takes the smallest index to get the first one. Opera is the other way around, opera is at the very back of the agent, so other browsers may differ.

/**
 * Description of Browser
 *
 * @author      Samet Tarim
 * @link        http://www.tnado.com/
 */    
var _MBT_Browser = {
    client: {},
    __init: function () {

        console.log('Init Browser...');

        _MBT_Browser.client.agent = navigator.userAgent;
        _MBT_Browser.set();
    },
    set: function () {

        var browsers = ["Firefox", "MSIE", "Trident", "Safari", "Chrome", "OPR"]; // Set the browser we want to detect
        _MBT_Browser.get(browsers);
        if (_MBT_Browser.client.current) {
            document.documentElement.setAttribute('data-useragent', _MBT_Browser.client.current); // Ad HTML tag data-useragent="IE"
        }
    },
    get: function (browser) {

        var index = '',
            i = 0,
            max = 0,
            min = 1000000; // to get the min value, we set first to million, is a placeholder for the first loop

        for (; i < browser.length; i++) {

            index = _MBT_Browser.client.agent.indexOf(browser[i]); // get index

            // Special case, we need here the largest index
            if (browser[i] === "OPR") {
                if (index > -1 && index > max) {
                    min = index;
                    _MBT_Browser.client.current = browser[i].toLowerCase();
                }
            } else {
            // We hold only the smallest index number and overwrite on smaller
                if (index > -1 && index < min) {
                    min = index;
                    _MBT_Browser.client.current = browser[i].toLowerCase();
                }
            }
        }
    }
};

Use:

document.addEventListener('DOMContentLoaded', function () {
    _MBT_Browser.__init();
});

And use with CSS to style on the browser:

[data-useragent="firefox"] {
    /* Attribute has this exact value */
}
prod3v3loper
  • 124
  • 10
-4

You can use navigator.userAgent for this. Just see if it contains Mozilla

Thomas Schaub
  • 418
  • 2
  • 9
  • 6
    Pretty much everything includes the string *Mozilla* … including Safari on the iPhone! This is useless for determining if Firefox is being used, it is useless for determining if a computer is being used! – Quentin Feb 24 '10 at 10:19
  • 1
    Have a look at http://www.nczonline.net/blog/2010/01/12/history-of-the-user-agent-string for a detailed history of the infamous *Mozilla* tag. – Marcel Korpel Feb 24 '10 at 18:53