HTML and CSS Reference
In-Depth Information
10.1 Browser Sniffing
For as long as there has been more than one browser in popular use, developers
have tried to differentiate between them to either turn down unsupported browsers,
or provide individual code paths to deal with differences between them. Browser
sniffing mainly comes in two flavors; user agent sniffing and object detection.
10.1.1 User Agent Sniffing
Sniffing the user agent is a primitive way of detecting browsers. By inspecting the
contents of the User-Agent HTTP header, accessible through navigator.
userAgent , script authors have branched their scripts to run IE specific code for
IE and Netscape-specific code for Netscape, or commonly, deny access to unsup-
ported browsers. Unwilling to have their browsers discriminated against, browser
vendors adjusted the User-Agent header sent by the browser to include strings
known to allow the browser access. This is evident to this day; Internet Explorer still
includes the word “Mozilla” in its user agent string and Opera stopped identifying
itself as Internet Explorer not too long ago.
As if browsers with built-in lies weren't enough, most browsers today even allow
their users to manually choose how the browser should identify itself. That's about
as unreliable identification as you can find.
Event handling has traditionally been rocky terrain to cover consistently across
browsers. The simple event properties we used in Chapter 9, Unobtrusive JavaScript,
is supported by just about any browser in use today, whereas the more sophisticated
EventListener interface from the level 2 DOM specification is not. The spec
calls for any Node to implement this interface, which among other things define
the addEventListener method. Using this method we can add numerous event
listeners to an event for a specific element, and we needn't worry about the event
property accidentally being overwritten.
Most browsers available today support the addEventListener method,
unfortunately with the exception of Internet Explorer (including version 8). IE
does, however, provide the attachEvent method, which is similar and can be
used to emulate common use cases. A naive way to work around this could involve
the use of user agent sniffing, as seen in Listing 10.1.
Listing 10.1 Browser sniffing to fix event listening
function addEventHandler(element, type, listener) {
// Bad example, don't try this at home
if (/MSIE/.test(navigator.userAgent)) {
Search WWH ::

Custom Search