Serving different Web pages or services to different browsers are usually bad practices. The Web aimed at a complete accessibility, and at browser agnosticism. Numerous good practices has been identified during the year like progressive enhancement, feature detection or how to write future-compatible Web sites.
But browsers and standards are not perfect and there are still some edge cases where detecting the browser is needed. Using the user agent to detect the browser looks simple, but doing it well is in fact a very hard problem. This document will guide you in doing this as much correctly as possible.
Before relying to browser detection...
When considering the detection of the browser using the user agent, the first step is to try to avoid it. Start by identifying why you want to browser detection:
- Do you want to go around a specific bug in some version of a browsers?
Look, or ask, in specialized forums: you're unlikely to be the first to hit this problem. Also experts, or simply people with another point of view, can give you ideas for working around the bug.
Sometimes start by checking if this bug has been reported to the browser vendor, don't hesitate to asks on forum or to report it on their bug tracking system (For Mozilla: https://bugzilla.mozilla.org ; For Webkit: http://bugs.webkit.org; For Opera: https://bugs.opera.com/) This step may seems unuseful, but it is not! First, contrary to the popular belief, browser makers pay attention to bug reports (though some may pass unnoticed through their triaging teams); second, analysis may hint about other work-around the bug; third, without a bug report, the odds that the bug will be corrected in the futur is lower.
- Do you want to check the existence of a specific feature?
Your Web site needs some modern feature and some Web browser still don't detect it. You would like to send to them the old Web site, less fancy, but that you know is working.
This is the worst case for user-agent sniffing: you don't know what will happen in the future and what browsers unknown to you are supporting. You should try to avoid this case as much as possible.