Browser Compatibility: Browser Detection - Doc JavaScript | WebReference

Browser Compatibility: Browser Detection - Doc JavaScript


Browser Detection

JavaScript features several properties that reflect the user's browser and platform specifications. These properties belong to the navigator object, which is supported by all JavaScript-enabled browsers.

Take a look at the following script:

<SCRIPT LANGUAGE="JavaScript">
<!--
var bName = navigator.appName;
var bVer = parseFloat(navigator.appVersion);
if (bName == "Netscape")
  var browser = "Netscape Navigator"
else
  var browser = bName;
document.write("You are currently using ", browser, " ", bVer, ".");
// -->
</SCRIPT>

This script prints the name of the browser and its version (as an integer). For example, it might print:

You are currently using Netscape Navigator 4.

The property navigator.appName is a string that reflects the name of the user's browser, such as "Netscape" or "Microsoft Internet Explorer".

The property navigator.appVersion reflects the browser's version. However, it is a string because it contains more than just the version number. For example, the value of this property might be "4.03 [en] (Win95; I)". Use the parseFloat() function to convert this property into a floating-point number that represents the version number only (e.g., 4.03).

Take a look at the following functions:

function bName() {
  // return 1 for Internet Explorer
  if (navigator.appName == "Microsoft Internet Explorer")
    return 1;
  // return 2 for Navigator
  if (navigator.appName == "Netscape")
    return 2;
  // return 0 for other browsers
  return 0;
}
function bVer() {
  // return version number (e.g., 4.03)
  return parseFloat(navigator.appVersion)
}

You can use these functions to execute a script segment only if the user is running Microsoft Internet Explorer 4.0+ or Netscape Navigator 4.0+:

var nameCode = bName();
var versionCode = bVer();
if ((nameCode != 0) && (versionCode >= 4)) {
  // additional statements here
}

http://www.internet.com

Created: November 4, 1997
Revised: December 4, 1997
URL: http://www.webreference.com/js/column6/browser.html