home | O'Reilly's CD bookshelfs | FreeBSD | Linux | Cisco | Cisco Exam  


Previous Section Next Section

5.1 Detecting the Browser Brand

NN 2, IE 3

5.1.1 Problem

You want script execution to branch one way for Netscape Navigator users and another for Internet Explorer users.

5.1.2 Solution

Use the navigator.appName property to find out which brand the browser purports to be. The following statement sets global Boolean variables for browser brands:

var isNav = (navigator.appName =  = "Netscape");
var isIE = (navigator.appName =  = "Microsoft Internet Explorer");

5.1.3 Discussion

The navigator.appName property returns a string that the browser maker determines. Netscape Navigator and Mozilla always return the string "Netscape", while Internet Explorer returns "Microsoft Internet Explorer". These strings and the equivalency operator are case-sensitive.

You will also encounter some interesting aberrations to this scheme once you roam from the IE and NN spheres. The Opera browser, for example, reports that its appName is "Microsoft Internet Explorer", "Netscape", or "Opera", depending on how the user sets the preferences. Settings for IE and NN force the browser to react to script syntax and objects along the lines of the selected browser (at least for simple tasks). If you want to find out for sure whether the browser is Opera, you must dig into the navigator.userAgent property, which contains more information about the browser. Here is the default value for the navigator.userAgent property from Opera 6:

Mozilla/4.0 (compatible; MSIE 5.0; Windows 98) Opera 6.03 [en]

The Opera-ness of this information is the string "Opera" buried within that string. Rather than look for the string at a particular location within the string (which has changed over time), you can simply test whether "Opera" is contained by navigator.userAgent:

var isOpera =   (navigator.userAgent.indexOf("Opera") != -1);

With respect to Internet Explorer, you should be aware that substantial differences exist between the Windows and Macintosh versions. Thus, you may need operating-system detection as well (covered in Recipe 5.5).

5.1.4 See Also

Recipe 5.2 through Recipe 5.4 for more granular browser version sniffing; Recipe 5.5 for operating-system detection.

    Previous Section Next Section