13.6. The Navigator ObjectThe Window.navigator property refers to a Navigator object that contains information about the web browser as a whole, such as the version and a list of the data formats it can display. The Navigator object is named after Netscape Navigator, but it is also supported by Internet Explorer. IE also supports clientInformation as a vendor-neutral synonym for navigator. Unfortunately, Netscape and Mozilla do not support this property. The Navigator object has five main properties that provide version information about the browser that is running:
The following lines of JavaScript code display each of these Navigator object properties in a dialog box: var browser = "BROWSER INFORMATION:\n"; for(var propname in navigator) { browser += propname + ": " + navigator[propname] + "\n" } alert(browser); Figure 13-2 shows the dialog box displayed when the code is run on IE 6. Figure 13-2. Navigator object propertiesAs you can see from Figure 13-2, the properties of the Navigator object have values that are sometimes more complex than we are interested in. We are often interested in only the first digit of the appVersion property, for example. When using the Navigator object to test browser information, we often use methods such as parseInt( ) and String.indexOf( ) to extract only the information we want. Example 13-3 shows some code that does this: it processes the properties of the Navigator object and stores them in an object named browser. These properties, in their processed form, are easier to use than the raw navigator properties. The general term for code like this is a "client sniffer," and you can find more complex and general-purpose sniffer code on the Internet.[47] For many purposes, however, something as simple as that shown in Example 13-3 works just fine.
Example 13-3. Determining browser vendor and version/* * File: browser.js * Include with: <script SRC="browser.js"></script> * * A simple "sniffer" that determines browser version and vendor. * It creates an object named "browser" that is easier to use than * the "navigator" object. */ // Create the browser object var browser = new Object( ); // Figure out the browser's major version browser.version = parseInt(navigator.appVersion); // Now figure out if the browser is from one of the two // major browser vendors. Start by assuming it is not. browser.isNetscape = false; browser.isMicrosoft = false; if (navigator.appName.indexOf("Netscape") != -1) browser.isNetscape = true; else if (navigator.appName.indexOf("Microsoft") != -1) browser.isMicrosoft = true; Copyright © 2003 O'Reilly & Associates. All rights reserved. |
|