Get IE Version from the User-Agent
var ie = 0;
try { ie = navigator.userAgent.match( /(MSIE |Trident.*rv[ :])([0-9]+)/ )[ 2 ]; }
catch(e){}
How it works: The user-agent string for all IE versions includes a portion "MSIE space version" or "Trident other-text rv space-or-colon version". Knowing this, we grab the version number from a String.match()
regular expression. A try-catch
block is used to shorten the code, otherwise we'd need to test the array bounds for non-IE browsers.
Note: The user-agent can be spoofed or omitted, sometimes unintentionally if the user has set their browser to a "compatibility mode". Though this doesn't seem like much of an issue in practice.
Get IE Version without the User-Agent
var d = document, w = window;
var ie = ( !!w.MSInputMethodContext ? 11 : !d.all ? 99 : w.atob ? 10 :
d.addEventListener ? 9 : d.querySelector ? 8 : w.XMLHttpRequest ? 7 :
d.compatMode ? 6 : w.attachEvent ? 5 : 1 );
How it works: Each version of IE adds support for additional features not found in previous versions. So we can test for the features in a top-down manner. A ternary sequence is used here for brevity, though if-then
and switch
statements would work just as well. The variable ie
is set to an integer 5-11, or 1 for older, or 99 for newer/non-IE. You can set it to 0 if you just want to test for IE 1-11 exactly.
Note: Object detection may break if your code is run on a page with third-party scripts that add polyfills for things like document.addEventListener
. In such situations the user-agent is the best option.
Detect if the Browser is Modern
If you're only interested in whether or not a browser supports most HTML 5 and CSS 3 standards, you can reasonably assume that IE 8 and lower remain the primary problem apps. Testing for window.getComputedStyle
will give you a fairly good mix of modern browsers, as well (IE 9, FF 4, Chrome 11, Safari 5, Opera 11.5). IE 9 greatly improves on standards support, but native CSS animation requires IE 10.
var isModernBrowser = ( !document.all || ( document.all && document.addEventListener ) );