In Javascript, how do I determine if my current browser is Firefox on a computer vs everything else?

后端 未结 13 1891
萌比男神i
萌比男神i 2020-12-01 07:13
if(firefox and is on a computer){
alert(\'using firefox on a computer\')
}else{
alert(\"using something else!\");
}

How can I do this?

13条回答
  •  南笙
    南笙 (楼主)
    2020-12-01 07:57

    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.)

提交回复
热议问题