17

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

If browser == IE6 {
    alert('hi');
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
TIMEX
  • 259,804
  • 351
  • 777
  • 1,080

9 Answers9

33

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.

Bjorn
  • 69,215
  • 39
  • 136
  • 164
  • 7
    Should be. Conditional comments are something introduced by Microsoft as a way to only run certain code in (specific versions of) IE. Because they are in HTML comments, other browsers will ignore it. – Aistina Feb 04 '10 at 00:27
  • 2
    Conditional comments are not a viable alternative. While they work in IE directly, they can be disabled in other similar browser when using the WebBrowser Control. In which case your conditional comment becomes useless. Most third-party browser using the Trident4 engine have conditional comments turned off. – Andrew Moore Feb 04 '10 at 00:39
  • 6
    And what other browsers are that? If you're going to support third party browsers using Trident4 you're going to have more issues than just conditional comments not working...you might as well support W3.org's Amaya. Ignore Andrew's comment, conditional comments always work for "down-level" browsers. – Bjorn Feb 04 '10 at 02:39
  • 3
    Also conditional comments are Microsoft's recommended way of targeting IE6. – Bjorn Feb 04 '10 at 02:47
  • 3
    @apphacker: Internet Explorer 6 uses the Trident 4 engine, but I guess that's beside the point... – Andrew Moore Feb 04 '10 at 03:50
  • 1
    I know that, I was talking about *third party* browsers using Trident4...especially ones with various options disabled. – Bjorn Feb 04 '10 at 14:24
  • 2
    Downvoted simply because the original question contains the term "using Javascript". HTML conditional comments are not a Javascript solution. And when you're writing portable Javascript, like a Javascript library, you need a Javascript solution. – thomasrutter Mar 31 '10 at 04:50
  • 1
    UPVOTED because it's the best IE detection solution I have ever thought about. HTML conditional comment are a Javascript solution for IE, which is exactly what the TIMEX is asking here. – Marco Demaio Nov 12 '10 at 20:51
  • 1
    @thomas: See [this function](https://gist.github.com/527683) which you can easily incorporate inside a library. – Marcel Korpel Nov 12 '10 at 22:51
29

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
}
thomasrutter
  • 114,488
  • 30
  • 148
  • 167
  • 10
    +1 Thanks for actually answering the question and not going on a rant as to why feature detection should be used, browser detection is still completely valid in some cases. – Lightweight Jul 25 '12 at 03:14
  • 3
    Feature detection is preferable when feature detection is actually what you want to do (which it probably is, in *most* cases when people ask about browser detection). When you need to apply a work around for a bug in a specific browser version, however, feature detection often isn't possible (for example, maybe it's a rendering bug, so it can't be "detected"). If you do use browser detection based on the user-agent you need to make sure the regex only targets the specific buggy version, and not future versions - or your code will break when future versions of the browser "fix" the bug. – thomasrutter Jul 25 '12 at 05:04
  • My reason for searching for this information is to detect IE6 within a HTC file, which is already defacto sniffed as Internet Explorer, but IE6 and IE8, 9, 10, 11, 12. Do not require the same solutions to fix CSS. Your answer to the question also answers my question. I would love to be in a world where IE browsers worked to standards, But I'm not, and giving those users defective pages does not represent the brands I work with. For good or bad, (mostly bad), I've got to deal with IE. – Wayne Dec 17 '13 at 18:25
  • Wait, isn't regex not supported on ie6? This may not pass. –  Mar 01 '19 at 14:28
  • RegExp support in Javascript goes back at least to Netscape 4 and IE5 – thomasrutter Mar 01 '19 at 22:56
  • Why the check for window.opera? – PHP Guru Nov 13 '20 at 18:35
  • Putting aside the fact question is pretty obsolete and nobody should have any reason for checking for IE6 anymore in 2020, the reason you exclude Opera is that some versions of Opera included "MSIE 6" in their user-agent string as a way of claiming compatibility with it. All browsers do this kind of thing even today, with every modern browser claiming compatibility with "mozilla", and Chrome/Edge etc claiming compatibility with Safari, AppleWebKit, KHTML and Gecko – thomasrutter Nov 16 '20 at 00:17
7
  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

Hannoun Yassir
  • 20,583
  • 23
  • 77
  • 112
  • 1
    -1: Never use user-agent to identify a browser. Use feature-based detection instead. – Andrew Moore Feb 04 '10 at 00:16
  • Why what is the reason ? it woks fine on IE, FF and chrome ! – Hannoun Yassir Feb 04 '10 at 00:23
  • @Yassir: The are a lot of browsers out there using the same engine (Trident 4) as MSIE 6. Using feature detection versus user agent detection catches those. It also has less false positives than user agent detection (a lot of browser have an option to change their UA to pass as another browser). – Andrew Moore Feb 04 '10 at 00:30
  • 11
    Why are you downvoting this answer? Yes, feature detection is ok but he's answering the OP's question properly. Pretty sure the OP didn't ask for anal evangelism about how feature detection > browser detection in some circumstances. – Will Morgan Feb 04 '10 at 13:01
  • 1
    Finally an answer to the actual question asked. However, it's not very concise. A regular expression is going to be much nicer. – thomasrutter Mar 31 '10 at 04:57
  • 2
    @Andrew, nobody asked about how to detect browsers which are not IE6 but which do use Trident. The question is *specifically* about IE6 – kibibu Mar 31 '10 at 05:08
5

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);
}
Nick Craver
  • 623,446
  • 136
  • 1,297
  • 1,155
Andrew Moore
  • 93,497
  • 30
  • 163
  • 175
  • 2
    This doesn't seem like the feature detection you're recommending in your comments to other answers to this question. – Tim Down Feb 04 '10 at 00:45
  • @Tim Down: I said feature **-based** detection, not feature detection. Feature-based detection tried to identify an **engine** based on features implemented in the JavaScript engine of that particular rendering engine. Feature detection allows you to turn on or off features based on if it was detected as supported. Knowing the engine used to render the page allows you to fix quirks with the rendering of dynamic elements on that page. This method is also called object-based detection. – Andrew Moore Feb 04 '10 at 00:47
  • 4
    This is feature inference, and flaky. What inferences would/should you make based on the existence of `document.getBoxObjectFor` or `window.mozInnerScreenX` or `navigator.taintEnabled`? If you're going to use these to vary behaviour that is unrelated to these objects being tested, it's only a small step up from examining the userAgent string to me. These objects may be overridden by JavaScript and are generally non-standard and therefore subject to the whims of browser manaufacturers: MooTools was stung by this quite recently (http://ajaxian.com/archives/mootools-call-to-upgrade). – Tim Down Feb 04 '10 at 10:55
  • 4
    Not wanting to single out this answer, but in general, I am so tired of seeing answers to questions on Stackoverflow that basically say "don't do that". Can't we just trust that the question asker has a good reason to specifically detect IE6, rather than do feature-based detection? For example, maybe the question asker wants to implement a warning to users saying "your version of Internet Explorer is out of date". – thomasrutter Mar 31 '10 at 04:54
4

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);
Tim Down
  • 318,141
  • 75
  • 454
  • 536
1

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:

Community
  • 1
  • 1
Dan Herbert
  • 99,428
  • 48
  • 189
  • 219
  • Let's say there is a rendering bug in a particular browser version that you want to work around, but ONLY target your workaround to that browser and version (for instance, let's say that transparent backgrounds render wrongly on buttons or something). There is no such thing as feature detection in that scenario - you can't "feature detect" a rendering bug. In the real world, not every quirk in a browser can be feature-detected, and you can't just assume that people asking about browser detection are less knowledgeable than you or have no good reason to do it. – thomasrutter Oct 22 '12 at 00:27
  • @thomasrutter Not all rendering bugs are impossible to feature detect. But, in general, rendering bugs are a CSS issue which have their own set of strategies that are separate from browser-specific JavaScript. This question was specifically asking about *JavaScript*, which *almost* never needs browser detection if written correctly. The asker was not specific about the reason for wanting to do browser detection, and there are already enough IE6-detection strategies mentioned here. I've provided an alternative that the asker may not have been aware of that will work out better for 90% of cases. – Dan Herbert Oct 22 '12 at 15:17
  • Colour me impressed that you came back to respond to a new comment on a post you made over 2 years ago :) – thomasrutter Oct 24 '12 at 01:16
1

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

Community
  • 1
  • 1
Jacco
  • 23,534
  • 17
  • 88
  • 105
  • That isn't technically conditional comments: it's called conditional compilation and is a separate mechanism. It's also not possible to use it to accurately detect the version of IE that is running because JScript can be upgraded independently of the browser. – Tim Down Oct 15 '12 at 21:30
0
<!--[if (IE 6)|(IE 7)]>
<script>
    alert("Lesser browser detected!");
</script>
<![endif]-->
ben
  • 653
  • 2
  • 7
  • 16
0

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/.

jhchen
  • 14,355
  • 14
  • 63
  • 91
  • 2
    Is it really a good idea to recommend someone use a massive JavaScript library or framework for a simple problem that requires nothing of the kind for the solution? – Bjorn Feb 04 '10 at 02:50
  • I wouldn't call jQuery "massive." What the poster is asking how to do is something that pretty much shouldn't be done so a more valuable piece of advice is why that is and what he/she should be doing instead so that he/she follows good programming practice. – jhchen Feb 04 '10 at 07:47