Java Reference
In-Depth Information
The key difference in this example is the if ... else statement at the bottom of the JavaScript code:
if (typeof navigator.geolocation != "undefined") {
navigator.geolocation.getCurrentPosition(geoSuccess, geoError);
} else {
alert("This page uses geolocation, and your " +
"browser doesn't support it.");
}
Here, you use the typeof operator on navigator.geolocation to determine if the browser supports
that feature. If it does, the getCurrentPosition() method is called.
If the browser doesn't support geolocation, the code displays a message to the user stating that his or
her browser doesn't support the necessary feature. If you had attempted to use geolocation without
ensuring that the browser supports it, the browser would throw an error.
Feature detection is extremely useful, and it enables you to isolate browsers based on the features
they do or don't support. But browser makers are not perfect, and they sometimes release a version
of a browser that exhibits unique and quirky behavior. In these cases, you need to isolate an
individual browser, and feature detection rarely gives you that fine level of control.
Browser sniffing
First, let us reiterate this point: Most of the time, you want to use feature detection. Browser sniffing
has many drawbacks, one of which is that some less common browsers may falsely identify themselves
as a more common browser. Another problem is that browser sniffing relies on the browser's user‐agent
string , which is a string that identifies the browser, and browser makers can drastically change the user‐
agent string between different versions (you see an example of this later). You should use the techniques
contained in this section only when you need to target a single browser for its own quirky behavior.
The navigator object exposes two properties that are useful in identifying a browser: appName and
userAgent . The appName property returns the model of the browser, such as “Microsoft Internet
Explorer” for IE or “Netscape” for Firefox, Chrome, and Safari.
The userAgent property returns a string containing various bits of information, such as the browser
version, operating system, and browser model. However, the value returned by this property varies
from browser to browser, so you have to be very, very careful when using it. For example, the
browser's version is embedded in different locations of the string.
trY it out Checking for and Dealing with Different Browsers
In this example, you create a page that uses the aforementioned properties to discover the client's
browser and browser version. The page can then take action based on the client's specifications.
<!DOCTYPE html>
<html lang="en">
<head>
<title>Chapter 8, Example 5</title>
</head>
<body>
 
Search WWH ::




Custom Search