How should I detect the IE browser?

jfriend00 picture jfriend00 · Aug 29, 2012 · Viewed 10.8k times · Source

I've already done feature detection on a particular feature to decide if I can use it or whether I have to use a work-around. But, unfortunately, I found that IE has some bugs in that feature that render it useless to me even when it's present. So, even though it passes the feature detection, I need to detect that the browser is IE so I don't use that feature if it's IE.

I've tried to see if I could do feature detection on the actual buggy behavior (which would be best because it would adapt if IE fixes the behavior in the future), but there does not appear to be any way to do that (subject of a different question). That means I'm left with trying to conclusively identify that it's an IE browser so I can avoid the buggy feature. I do not want to use the useragent string since we all know that it is easily spoofed and can easily be wrong.

So, I'd like to do feature detection on whether it's the IE browser or not.

The approach I have so far is this:

var isIE = (document.body.attachEvent && window.ActiveXObject);

This looks to see if the attachEvent() method is present and if ActiveXObject support is present. I had to do more than just the attachEvent check because Opera supports attachEvent.

Is this a reliable way to detect IE? Are there better ways?

Please don't respond with I really shouldn't do browser detection, but should use feature detection instead. I'm already doing feature detection, but that caused a problem because a browser that "supports" the feature and thus passes feature detection turns out to be so buggy that I can't use the feature in that browser. So, now I must detect the buggy browser.

If you want to know more about the specific situation this is being used in, it's described in this other question.

Answer

Jeremy J Starcher picture Jeremy J Starcher · Aug 29, 2012

Conditional comments conditional compilation, explained here:

http://www.quirksmode.org/css/condcom.html

Or the related cousin found here:

http://www.javascriptkit.com/javatutors/conditionalcompile.shtml

Both are Internet Explorer exclusive, so they will allow you to sniff IE.

<script type="text/javascript">

/*@cc_on
document.write("JScript version: " + @_jscript_version + ".<br>");
   /*@if (@_jscript_version >= 5)
      document.write("JScript Version 5.0 or better.<br \/>");
      document.write("This text is only seen by Internet Explorer browsers that support JScript 5+<br>");
   @else @*/
      document.write("This text is seen by all other browsers (ie: Firefox, IE 4.x etc)<br>");
   /*@end
@*/

</script>