b++ 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
truein all Internet Explorer versions and also in Opera window.opera- also known as
operaobject, returnstruein Opera window.XMLHttpRequest- returns
truein Firefox, Opera, Safari and IE 7 - returns
falsein 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]––>
001—2006.10.31.21:07
You don’t need to use the triadic operator, as your bracketed condition returns a Boolean value. Just use
var ie7 = (document.all && !window.opera && window.XMLHttpRequest);
(although the Conditional Comment method is rather elegant, IMHO.)
002—2006.10.31.21:56
Wow, great tip about window.XMLHttpRequest, which I might find a use for, very soon.
003—2006.11.01.00:09
The best approach is not to test for browsers in general, but to test for only those features you need. If you need document.all, test for it, not for a particular version of IE.
004—2006.11.01.16:56
Berislav, sometimes you simply can’t test for a method or object property.
Testing
typeof document.style.minHeightreturnsstringin all IE versions, but in IE 6 and lower, you can’t actually apply it, due to unsupported CSS propertymin-height.What’s even worse, some other
element.styleobject properties, that have unsupported CSS counterparts in IE 6 or lower (for exampledocument.style.maxHeight) return expectableundefined, so there’s no key one could rely on.Or maybe I’m missing something here…
005—2006.11.01.17:02
Nick, true that… thanks!
006—2006.11.15.21:12
You could use conditional compilation… untested but should work…
isIE7 = false;
/*@cc_on
@if (@_jscript_version == 7)
isIE7 = true;
@end
@*/
007—2006.11.18.01:41
Unfortunately, IE7 has an option to disable native support for XMLHTTP. Unchecking Tools > Options > Advanced > “Enable native XMLHTTP support” causes window.XMLHttpRequest to be undefined. Tested using following block:
<script>document.write(window.XMLHttpRequest);
</script>
008—2006.11.21.14:19
Incidentally the correct _jscript_version value for IE7 is 5.7. (Similarly, IE6 is 5.6.)