Detecting browsers correctly
Martin Kopta is certainly right when he says that
the document.all collection doesn’t uniquely identify
browsers in the Internet Explorer family.
The problem arises when, on
the client side, you need to find out the browser version and decide which piece of code to run, for example. It’s not uncommon for
a browser to lack or incorrectly implement
standard DOM methods
or other technologies, so you have to use its own browser-specific solution.
One of the most common ways to detect browsers in the Internet Explorer family
is to test for the document.all collection. This usually takes
the following form:
if(!document.all){
//standardni vetev kódu
}else{
//proprietární využití pro IE
}But that very construction sends browsers such as Opera down
the Internet Explorer branch. When it sees document.all
, Opera returns an Object in response, so it can get into the part of the code that
may cause an error.
The lesson is that it pays to test for features that really are specific, or proprietary, to
the particular JavaScript or JScript implementation or technology.
You should be able to detect Opera reliably by checking window.opera. Internet
Explorer 4.01 can be detected using window.print. For later versions
of Internet Explorer I’d recommend its particular implementation of events instead
(the Event object). For more on the subject, see
Eddie Traversa’s article
Object Detection in the New Browser Age
The question remains how to detect newer versions that may drop their proprietary
technologies. For reasons such as backward compatibility, however, we can’t
expect that to happen. I’d tackle the problem case by case. There’s always
a bug or difference to be found …
Related articles
Related CZ Podcast episodes
- #217 · Ivo Lukačovič
On Windy, JavaScript and building companies. · Czech audio
- #3 · Java 6 SE, Vývoj webových aplikací
Dagi and Filemon discuss Java 6 and web application frameworks. · Czech audio