JavaScript EditorFree JavaScript Editor     DHTML Editor 

Main Page Previous Section Next Section

5.3 Detecting the Internet Explorer Version

NN n/a, IE 3

5.3.1 Problem

You want script execution to branch based on a specific or minimum version of Internet Explorer.

5.3.2 Solution

Access the complete version number by parsing the string of the navigator.userAgent property. Internet Explorer identifies itself with the string MSIE, followed by a space, the version number (with one or more digits to the right of the decimal), and a semicolon. Here's a function that returns the numeric portion of the pertinent information:

function getIEVersionNumber( ) {
    var ua = navigator.userAgent;
    var MSIEOffset = ua.indexOf("MSIE ");
    if (MSIEOffset =  = -1) {
        return 0;
    } else {
        return parseFloat(ua.substring(MSIEOffset + 5, ua.indexOf(";", MSIEOffset)));

You can use the returned value to establish a global variable that gets used elsewhere in code execution branch condition statements. For example, here's how to execute code only if the browser identifies itself as being compatible with IE 5 or later:

var isIE5Min = getIEVersionNumber( ) >= 5;
if (isIE5Min) {
    // perform statements for IE 5 or later

5.3.3 Discussion

Because the function in the Solution returns a number data type, it does not reveal whether the version number is followed by any letters, such as B for beta versions. If you omit the parseFloat( ) function, the returned result will be a string value. But by and large, you will be looking for a numeric value to use for a comparison, as shown previously.

Using a numerical comparison of the version number is a two-edged sword. On one side is a warning against using a simple equality operator (= =) instead of a greater-than or equals operator (>=). Using the equality operator is a frequent mistake of a routine that is designed to run on only the latest version. The problem with this is that when the next version appears, the comparison operation fails. On the other side is that the >= operator assumes that future versions of the browser will continue to support the branched feature. While browsers tend to be backward-compatible, scripters familiar with the removal of the layer object between Netscape Navigator 4 and 6 know how this assumption can get you into trouble. This is one more reason to look toward object detection rather than version detection in most cases. Version detection is valuable, however, when you are aware of a bug in a particular version and you want your script to bypass that bug when running on the rogue browser.

5.3.4 See Also

Recipe 5.2 and Recipe 5.4 for additional browser detection tips; Recipe 2.1 for uses of the parseFloat( ) function; Recipe 1.5 for uses of the indexOf( ) method.

    Main Page Previous Section Next Section

    JavaScript EditorJavaScript Checker     DHTML Editor