↑
Main Page
Methods of Browser Detection
Methods of Browser Detection
Like most things in JavaScript, a few different forms of browser detection are available. Presently, two
approaches to browser detection are used: object/feature detection and user-agent string detection. Each
approach has its advantages and disadvantages, and you should understand proper usage of each when
you are deploying your Web solution.
Object/feature detection
Object detection (also called feature detection) is a generic way of determining a browser ’s capabilities
rather than the exact make and model of a target browser. Most JavaScript experts point to this method
as the most appropriate one to use because they believe it
future proofs
scripts against changes that might
make it difficult to determine the exact browser being used.
Object detection involves checking to see if a given object exists before using it. For instance, suppose
you want to use the DOM method
document.getElementById()
, but you aren’t sure if the browser
supports it. You can use the following code:
if (document.getElementById) {
//the method exists, so use it here
} else {
//do something else
}
The previous code checks whether the method exists. You have learned that a property (or method) that
doesn’t exist returns a value of
undefined
. You may also remember that the value
undefined
, when
translated into a Boolean, is equal to
false
. So, if
document.getElementById()
doesn’t exist, the code
skips to the
else
clause; otherwise the first set of code is executed.
This method of detection should be used when you are more concerned with the capabilities of the
browser than you are with its actual identity. Throughout the book, you see examples of object detection
used in specific instances, whereas in other instances another method, user-agent string detection is
most appropriate.
User-agent string detection
User-agent string detection is the oldest browser detection method there is. Every program that accesses
a Web site is required to provide a user-agent string identifying itself to the server. Traditionally, this
information was only accessible from the server in the CGI environment variable HTTP_USER_AGENT
(accessed by
$ENV{‘HTTP_USER_AGENT’}
). However, JavaScript introduced the
userAgent
property of
the
navigator
object to provide client-side access to the user-agent string:
var sUserAgent = navigator.userAgent;
Note that to check for the existence of a function, you must omit the parentheses. If
you include the parentheses, the interpreter tries to call the function, which causes
an error if the function doesn’t exist.
226
Chapter 8
11_579088 ch08.qxd 3/28/05 11:38 AM Page 226
Free JavaScript Editor
Ajax Editor
©
→