AJAX browser detection

January 2nd, 2006

If you have ever stumbled across Rasmus’s 30 second AJAX Tutorial, then you probably have the code copied, pasted, bookmarked or memorized. There are however a few limitations in this piece of code, especially with the upcoming release of IE7.

The javascript uses a small function to detect the browser.

function createRequestObject() {
    var ro;
    var browser = navigator.appName;
    if(browser == 'Microsoft Internet Explorer'){
        ro = new ActiveXObject("Microsoft.XMLHTTP");
    }else{
        ro = new XMLHttpRequest();
    }
    return ro;
}

Basically, if the browser has a User Agent of Microsoft Internet Explorer, then it is delivered an ActiveXObject rather than an XMLHttpRequest. This is fine for IE6 and below (actually quite necessary) but IE7 is set to be natively compatible with XMLHttpRequest, so we don’t want to be sending it ActiveX objects as well.

An easy way to overcome this is to use a browser compatibility check, rather than a user agent check, such as in the following example:


function createRequestObject() {
    var ro;
    try {
      ro = window.XMLHttpRequest ? new XMLHttpRequest():
    			new ActiveXObject("Microsoft.XMLHTTP");
    }
    catch (e) {
      ro = false;
    }
    return ro;
}

This checks if the browser supports XMLHttpRequest, and if it doesn’t, then and only then, it initiates the ActiveXObject. This is regardless of the user agent string being broadcast by the browser.

Obligatory warning: the above code has not been tested, and in fact has barely even been proof read, so it may not work without modification, but I am sure you will get the general gist of it. Also, Rasmus’s code has a few other failings, such as no provision for multiple xmlhttprequests, and issues with IE caching, so be warned.

This entry was posted on Monday, January 2nd, 2006 at 12:54 pm and is filed under Ajax. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

Leave a Reply

XHTML: Permitted tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>