Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

the best way to detect browser in js

There are lots of ways for browser detecting in JavaScript.

As far as i know, using navigator.userAgent or detecting features (like XMLHttpRequest) and so on.

Can anybody tell me which way is the best and most effective?

like image 624
vikingmute Avatar asked Oct 09 '11 08:10

vikingmute


2 Answers

If you really need to know what browser they're using, you mostly have to look at the userAgent string (although you can sometimes infer the browser by looking for a couple of obscure features). Just be aware that some browsers let the user change that and lie to you. :-)

But detecting the browser is out of fashion, for good reasons. Instead, as you say, you want to detect the features you're looking for. This is more reliable, and less work. Just because IE didn't support addEventListener, for instance, doesn't mean it never will (and in fact IE9 does). So you feature-detect instead, which future-proofs the code.

Here's a concrete example: Suppose you want to know (as I did for my place5 jQuery plug-in) whether a browser supports the placeholder attribute. You could use browser detection and maintain a list of which browsers in which versions have or don't have support, which is messy and something you have to keep coming back to, etc., etc., or you could do this:

if ("placeholder" in document.createElement("input")) {
    // The browser supports the attribute
}
else {
    // It doesn't
}

...and you're done.

There's a great set of feature tests in this page maintained by kangax. There's also a library called Modernizr that does feature detection, media queries, and more for you. If you use jQuery, it has some feature detection built in via jQuery.support. There's a nice discussion of various aspects of feature detection, media queries, form-factor detection (tablet, phone, or PC?) in this article.

like image 200
T.J. Crowder Avatar answered Nov 14 '22 21:11

T.J. Crowder


You do not detect browsers. Instead you check for available features.

Browsers detection can be worked around ( hell .. I had to do it myself when using opera on gmail few years ago ), but if browser has a feature, then you know that you can use it.

like image 20
tereško Avatar answered Nov 14 '22 21:11

tereško