Thursday, March 20, 2014

How to detect Internet Explorer 10 and higher?

For a long time detecting of Internet Explorer browser was easy using Conditional Comments, something like:

<!--[if IE]>
 <script type="text/javascript">
  var isIE = true;
 </script>
<![endif]-->

Starting version 10, Internet Explorer doesn't support conditional comments feature :(

Here is the JavaScript code to detect IE of any version since 5 till 11:

var isIE = (function(){
    var undef,rv = -1; // Return value assumes failure.
    var ua = window.navigator.userAgent;
    var msie = ua.indexOf('MSIE ');
    var trident = ua.indexOf('Trident/');

    if (msie > 0) {
        // IE 10 or older => return version number
        rv = parseInt(ua.substring(msie + 5, ua.indexOf('.', msie)), 10);
    } else if (trident > 0) {
        // IE 11 (or newer) => return version number
        var rvNum = ua.indexOf('rv:');
        rv = parseInt(ua.substring(rvNum + 3, ua.indexOf('.', rvNum)), 10);
    }

    return ((rv > -1) ? rv : undef);
}());
 

Hope Internet Explorer 12 and higher will work the same way :)