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?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
If you really need to know what browser they’re using, you mostly have to look at the
userAgentstring (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
placeholderattribute. 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:…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.