Share

From this page you can share Bad Object Detection to a social bookmarking site or email a link to the page.
Social WebE-mail
Enter multiple addresses on separate lines or separate them with commas.
Bad Object Detection
(Your Name) has forwarded a page to you from Ajaxonomy
(Your Name) thought you would like to see this page from the Ajaxonomy web site.

Bad Object Detection

Tagged:  

John Resig has written another great post, this time about bad object detection. The article talks about classic bad object detection such as checking if the document.all object exists to test for Internet Explorer (I admit it I've been guilty of this one).

Below is an excerpt from the post.

Fringe Cases From Global Variables

While they don't happen often for those that they do happen to they can be a living hell. Specifically when object detection takes place within the global object (e.g. window.opera) then all bets are off as to its cross-browser applicability. Let's take a look at an example:

<html>
<head>
<script>

window.onload = function(){
  if ( window.opera ) {
    alert("You're using Opera, pick me!");
  }
};
</script>

</head>
<body> 
  <h1>Which browser?</h1>
  <a href="http://mozilla.com/" id="firefox"> Firefox</a><br/>

  <a href="http://apple.com/" id="safari"> Safari</a><br/>
  <a href="http://opera.com/" id="opera"> Opera</a><br/>

  <a href="http://microsoft.com/" id="ie"> Internet Explorer</a>
</body>
</html>

You would expect the alert to pop up when the user visits the page in Opera - and it does - however the alert also comes up in Internet Explorer. This is because all elements with an ID are automatically introduced as global variables (in the above there are four globals: firefox, safari, opera, and ie that all reference their associated elements). This is a fantastically difficult bug to spot and work around - thus you should be very cautious when doing any form of object detection on the global object.

Of course, it almost goes without saying, that there could exist an 'opera' variable elsewhere in the site that could interfere with this detection. Although that would, arguably, be easier to detect as it would make every browser trigger a false positive.

There's two morals here:

  1. Only use object detection to detect exactly what you need to use.
  2. Be wary of detecting properties on the global object - it's capable of lying to you.

You can read the full post here.

This is a great post and something that I hadn't thought much about. I really like John's blog and I find his posts very informative. I have often found information on his blog that I haven't seen anywhere else on the web (I know that I've said it before, but if you don't have John's blog on your feed reader, I would recommend adding it).