Drainbamage.nl blog of Christiaan Ottow

3Jun/071

JavaScript Object Detection

Even though the times of the browser wars are gone, browser incompatibilities remain. New features are added with every new browser version. Some are copied by the other vendors in their next version, some aren't. And of course there is the battle between the W3C standards and the Microsoft way, particularly in Javascript event handling.
When creating a javascript-enhanced website, developers often run into these incompatibilities. The most obvious solution when encountering such a problem, is to detect which browser is being used. I'll illustrate this with an example.


function changeText( )
{
  var node = document.getElementById('nodeToChange');
  node.innerText = 'Hello, World!';
}

This piece of code is pretty straightforward: the function changeText changes the text within the node with id="nodeToChange" into "Hello, World!".

This code won't work in Firefox. You'll see nothing change in the node. Firefox uses the textContent property to change the contents of a text node. So, one would expect the solution to be to detect the browser that the visitor is using, using some advanced browser detection script or your own routines. The name of the browser is available in the navigator.userAgent property. But most of the time, this is a very poor solution. Let me explain why.

Post to Twitter Tweet This Post

   

Twitter links powered by Tweet This v1.7, a WordPress plugin for Twitter.