Using object detection to detect support for a property or method
"What on earth does the above 'if' statement detect?", you may ask. Well, whether the running browser supports the forms object or not. By putting an object's name inside an "if" statement, the statement evaluates to true only if the object is defined (is supported), thus the name "object detection".
Detecting support for a property or method
In both cases, if the visitor's browser doesn't support that property or method, it returns null, causing the "if" statement to evaluate to false (and hence the containing code not executed).
What to watch out for
When using object detection, you should always ensure that the parent object containing the property or method you wish to detect is supported first before testing for the property/ method itself. Otherwise, non supporting browsers will return an error, since it doesn't even recognize the object you're referencing, let alone whether that object supports a particular property or method! In cases where the parent object is a universal one such as "window" or "document", as in the above examples, there's no need to perform this check, but lets say your target property is "screen.pixelDepth". This property is only supported in Netscape and Firefox, not IE. Here's the correct way to test for it:
Notice how I first test for the screen object itself, then the "pixelDepth" property for it. This set up ensures that if the user's browser doesn't even support the screen object, the "if" condition immediately evaluates to false without testing for the second part of the expression, and the containing code is not executed.
- Tutorial Introduction
- Using object detection to detect support for a property or method
- Using object detection to sniff out different browsers