Reliable IE 7 detection with JavaScript?

Currently, the most accurate method of detecting Internet Explorer 7 with JavaScript is the following:

var ie7 = (document.all && !window.opera && window.XMLHttpRequest) ? true : false;

There’s an alternate, but in my opinion less future proof, method:

var ie7 = (typeof document.addEventListener != 'function' && window.XMLHttpRequest) ? true : false;

I don’t believe they will ever drop document.all, but I’m certain they are going to fix addEventListener method.

Test conditions

Here’s a quick breakdown of objects/methods tested:

document.all
returns true in all Internet Explorer versions and also in Opera
window.opera
also known as opera object, returns true in Opera
window.XMLHttpRequest
returns true in Firefox, Opera, Safari and IE 7
returns false in IE 6 and lower

So far, I haven’t found flaws in this detection method. However, if someone knows better, please do tell. Ken Snyder pointed out that the native XMLHttpRequest can be disabled in IE 7 by unchecking Tools -> Options -> Advanced -> “Enable native XMLHTTP support” option… Bummer!

Conditional Comments

Last, but not least, you can always set ie7 variable to true inside conditional comments:

<!––[if IE 7]>
<script type="text/javascript">ie7 = true;</script>
<![endif]––>

Marko Dugonjić is a designer specialized in user experience design, web typography and web standards. He runs a nanoscale user interface studio Creative Nights and organizes FFWD.PRO, a micro-conference and workshops for web professionals.

Interested in more content like this?