Browser Compatibility: Object Detection - Doc JavaScript | WebReference

Browser Compatibility: Object Detection - Doc JavaScript

Object Detection

Browser detection is not recommended because it checks what browser the user is running, not what features are supported. So if your script depends on browser detection to decide whether or not to execute a specific function or script segment, it might not work with future browers. The number of browsers and browser versions is constantly growing, and so is the number of inconsistent features. Furthermore, you must be a JavaScript hacker to know exactly what features are supported by each browser. Is window.onerror supported by Netscape Navigator 2.0? How about Microsoft Internet Explorer 3.0? With object detection you don't need to know!

As you already know, if you refer to an object (or a property, method, function, etc.) that is not supported, the browser cannot execute the script, and it displays a very annoying error message. Object detection simply checks if an object exists before you use it in the script. We used object detection in our column "Universal JavaScript Rollovers" to find out if the browser supports the document.images object before using it to swap the desired image:

if (document.images) {
  // rollover script here

The general syntax for object detection is:

if (the name of the required object) {
  // statements that use that object

A few restrictions apply to the object in the conditional statement:

We all know that an if statement requires a Boolean value. So why does it work with objects? The answer is very simple. An object that does not exist has a null value, which is a special one, because it converts to false when used in a statement that requires a Boolean expression.

Created: November 4, 1997
Revised: December 4, 1997