简体   繁体   中英

What is the best way to detect Internet Explorer 6 using JavaScript?

What is the best way to detect Internet Explorer 6 using JavaScript?

If browser == IE6 {
    alert('hi');
}

Conditional comments are a good alternative:

<!--[if IE 6]>
<script>
var everythingIsBroken = true;
</script>
<![endif]-->

Edit : If you're still looking to support IE 6 in 2017 or after ... well my heart goes out to you. The answer to this question in 2017 is really not to worry about IE 6. It's not a supported browser anymore. Any operating system that can run this browser and the browser itself are not getting security updates anymore. This means users using this software are at great risk of being exploited. This is a big problem for people who can't afford to upgrade.

At the risk of actually answering the question that was asked (and assuming for a moment the asker has a good reason to specifically detect IE6):

if (/\bMSIE 6/.test(navigator.userAgent) && !window.opera) {
  // yep, browser claims to be IE6
}
  var ua = window.navigator.userAgent;
  var msie = ua.indexOf ( "MSIE " );

  if ( msie > 0 )      // If Internet Explorer, return version number
     return parseInt (ua.substring (msie+5, ua.indexOf (".", msie )));
  else                 // If another browser, return 0
     return 0;

Source : http://support.microsoft.com/kb/167820

Don't base your detection on the user-agent. There are plenty of other browsers out there that use the Trident 4 engine (the one IE6 use) that are not IE6.

The answer is simple: don't detect the browser , detect the engine . To do that, you must use what's called feature based detection .


Using feature based detection has the following advantages:

  • Detects all browsers using similar rendering engine than target.
  • Easier code branching to work around issues of a rendering engine.
  • Less false positives (UAs can be modified to pass as another browser, features can't).

The following script uses browser features to detect the engine. Credit to The MooTools production team ( http://mootools.net/developers/ ).

Note: The snippet below has been modified to work without the MooTools javascript framework. If you do wish to work with MooTools , you no longer need this code, it is part of the distribution.

function $tryCatch(){
    for (var i = 0, l = arguments.length; i < l; i++){
        try {
            return arguments[i]();
        } catch(e){}
    }
    return null;
};

var Browser = {

    Engine: {name: 'unknown', version: 0},

    Platform: {name: (window.orientation != undefined) ? 'ipod' : (navigator.platform.match(/mac|win|linux/i) || ['other'])[0].toLowerCase()},

    Features: {xpath: !!(document.evaluate), air: !!(window.runtime), query: !!(document.querySelector)},

    Plugins: {},

    Engines: {

        presto: function(){
            return (!window.opera) ? false : ((arguments.callee.caller) ? 960 : ((document.getElementsByClassName) ? 950 : 925));
        },

        trident: function(){
            return (!window.ActiveXObject) ? false : ((window.XMLHttpRequest) ? ((document.querySelectorAll) ? 6 : 5) : 4);
        },

        webkit: function(){
            return (navigator.taintEnabled) ? false : ((Browser.Features.xpath) ? ((Browser.Features.query) ? 525 : 420) : 419);
        },

        gecko: function(){
            return (!document.getBoxObjectFor && window.mozInnerScreenX == null) ? false : ((document.getElementsByClassName) ? 19 : 18);
        }

    }

};

Browser.Platform[Browser.Platform.name] = true;

Browser.detect = function(){

    for (var engine in this.Engines){
        var version = this.Engines[engine]();
        if (version){
            this.Engine = {name: engine, version: version};
            this.Engine[engine] = this.Engine[engine + version] = true;
            break;
        }
    }

    return {name: engine, version: version};

};

Browser.detect();

Browser.Request = function(){
    return $tryCatch(function(){
        return new XMLHttpRequest();
    }, function(){
        return new ActiveXObject('MSXML2.XMLHTTP');
    }, function(){
        return new ActiveXObject('Microsoft.XMLHTTP');
    });
};

Browser.Features.xhr = !!(Browser.Request());

Browser.Plugins.Flash = (function(){
    var version = ($tryCatch(function(){
        return navigator.plugins['Shockwave Flash'].description;
    }, function(){
        return new ActiveXObject('ShockwaveFlash.ShockwaveFlash').GetVariable('$version');
    }) || '0 r0').match(/\d+/g);
    return {version: parseInt(version[0] || 0 + '.' + version[1], 10) || 0, build: parseInt(version[2], 10) || 0};
})();

function $exec(text){
    if (!text) return text;
    if (window.execScript){
        window.execScript(text);
    } else {
        var script = document.createElement('script');
        script.setAttribute('type', 'text/javascript');
        script[(Browser.Engine.webkit && Browser.Engine.version < 420) ? 'innerText' : 'text'] = text;
        document.head.appendChild(script);
        document.head.removeChild(script);
    }
    return text;
};

Just include this JavaScript class and you can detect IE6 and any other browser using the Trident4 engine by doing the following:

if(Browser.Engine.trident4) {
   alert('IE6 or similar...');
} elseif(Browser.Engine.name == "trident") {
   alert('Internet Explorer Trident Rendering Engine Version ' + Browser.Engine.version);
}

The most reliable way to do this is to use conditional comments, as mentioned by @apphacker. However, something that is seemingly less well-known is that conditional comments can be used in JavaScript:

var div = document.createElement("div");
div.innerHTML = "<!--[if IE 6]><i></i><![endif]-->";
var isIe6 = (div.getElementsByTagName("i").length == 1);

alert("Is IE 6: " + isIe6);

Very late addition.

In addition to the HTML conditional comments used in apphacker's answer , Microsoft's JScript implementation also provides conditional comments for JavaScript :

<script type="text/javascript">
    var isIE6 = /*@cc_on/*@if(@_jscript_version<=5.6)1@else@*/0/*@end@*/;

    if (isIE6) {
        alert("You're screwed");
    }
</script>

The good thing is that it can also be used in external JavaScript files ( .js ).

For a table listing the version of JScript that are implemented by Microsoft host applications: JavaScript Version Information

What is the best way to detect <browser_x> using JavaScript?

By not.

As Andrew Moore has mentioned in comments in this post, you should be using feature detection. This will make your code more "future-proof". If another browser includes, or no longer supports a feature in the future, then your code will be safe. There are a number of sites out there explaining how to handle this. The concept is huge and covers a lot of concepts, so rather than writing an essay/book on this, here are some resources to use:

<!--[if (IE 6)|(IE 7)]>
<script>
    alert("Lesser browser detected!");
</script>
<![endif]-->

I'm not sure if there's a special reason why you want to detect IE 6 but in general it is better to try to detect the browser's features rather than detecting the browser. You can do this easily with JQuery using jQuery.support: http://api.jquery.com/jQuery.support/ .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM