21st May, 2014

Reliably detect IE version with JavaScript

I found this snippet online to detect what version of IE using JavaScript. I didn't write it, if this is yours, please let me know and I'll attribute you.

function getInternetExplorerVersion() {
    var rv = -1; // Return value assumes failure.
    if (navigator.appName == 'Microsoft Internet Explorer') {
        var ua = navigator.userAgent;
        var re = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");
        if (re.exec(ua) != null)
            rv = parseFloat(RegExp.$1);
    }
    return rv;
}

 

Comments

  1. 23rd June 2014 Andrew said
    Great but doesn't work for IE11+ because IE11+ uses a different UA string. Here's a solution that takes into account IE11+ 
    
    Found on Stackoverflow : http://stackoverflow.com/a/17907562
    
    function getInternetExplorerVersion () {
    	var rv = -1;
    	if (navigator.appName === 'Microsoft Internet Explorer')	{
    		var ua = navigator.userAgent;
    		var re  = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");
    		if (re.exec(ua) !== null) {
    			rv = parseFloat(RegExp.$1);
    		}
    	} else if (navigator.appName === 'Netscape') {
    		var ua = navigator.userAgent;
    		var re  = new RegExp("Trident/.*rv:([0-9]{1,}[\.0-9]{0,})");
    		if (re.exec(ua) !== null) {
    			rv = parseFloat(RegExp.$1);
    		}
    	}
    	return rv;
    }

Add Comment

The opinions expressed here are my own and not those of my employer.