249

I want to bounce users of our web site to an error page if they're using a version of Internet Explorer prior to v9. It's just not worth our time and money to support IE pre-v9. Users of all other non-IE browsers are fine and shouldn't be bounced. Here's the proposed code:

if(navigator.appName.indexOf("Internet Explorer")!=-1){     //yeah, he's using IE
    var badBrowser=(
        navigator.appVersion.indexOf("MSIE 9")==-1 &&   //v9 is ok
        navigator.appVersion.indexOf("MSIE 1")==-1  //v10, 11, 12, etc. is fine too
    );

    if(badBrowser){
        // navigate to error page
    }
}

Will this code do the trick?

To head off a few comments that will probably be coming my way:

  1. Yes, I know that users can forge their useragent string. I'm not concerned.
  2. Yes, I know that programming pros prefer sniffing out feature-support instead of browser-type but I don't feel this approach makes sense in this case. I already know that all (relevant) non-IE browsers support the features that I need and that all pre-v9 IE browsers don't. Checking feature by feature throughout the site would be a waste.
  3. Yes, I know that someone trying to access the site using IE v1 (or >= 20) wouldn't get 'badBrowser' set to true and the warning page wouldn't be displayed properly. That's a risk we're willing to take.
  4. Yes, I know that Microsoft has "conditional comments" that can be used for precise browser version detection. IE no longer supports conditional comments as of IE 10, rendering this approach absolutely useless.

Any other obvious issues to be aware of?

Alex.K.
  • 3,342
  • 13
  • 38
  • 44
Chad Decker
  • 5,427
  • 8
  • 24
  • 30
  • 123
    "It's just not worth our time and money to support IE pre-v9". I wish I could do that. – Hassan Jun 09 '12 at 22:15
  • 2
    Based on point [2] I won't suggest Modernizr (http://en.wikipedia.org/wiki/Modernizr) - everyone has to draw a line in the sand somewhere - but IE9 does seem like a high line – amelvin Jun 09 '12 at 22:21
  • @Hassan: We have a small captive audience. Virtually all users are using decent browsers except for a few WinXP guys who are ineligible to upgrade to IE9. Those are the dudes that I'm targeting with this error message. – Chad Decker Jun 09 '12 at 22:52
  • @Andreas: Interesting thought. So using "conditional comments" in IE 10 won't cause IE10 to choke? They'll just be ignored? If so, then what you're saying makes a lot of sense. – Chad Decker Jun 09 '12 at 22:54
  • 1
    Conditional comments are just normal comments. Only IE interprets them as special ones. IE10+ won't do that anymore. – Andreas Jun 09 '12 at 22:56
  • 3
    Conditional comments will be treated exactly the same by IE 10 as non-IE browsers. They're valid HTML comments so will be treated as such. I agree with Andreas and think conditional comments is the way to go. – Tim Down Jun 09 '12 at 23:00
  • 1
    The official documentation that says IE10+ won't support conditional comments: http://blogs.msdn.com/b/ie/archive/2011/07/06/html5-parsing-in-ie10.aspx?Redirected=true - Thanks to: http://stackoverflow.com/a/9900331/320399 – blong Dec 18 '12 at 19:51
  • The selected answer is incorrect and doesnt work for ie11. see my answer – Royi Namir Jan 19 '15 at 08:26
  • 1
    Who cares if IE10 supports conditional comments if it's not one of the browsers you're trying to detect? You don't need to detect whether it's IE 9 or higher, you only need to detect whether it's IE8 or lower. Your mistake is in thinking you need to figure out what it is in order to figure out what it is not. That's not true. You don't need to detect IE10, you only need to know that it's NOT IE8 (or lower). Any code you put in a `lt IE 9` conditional will run in IE8 and below and nowhere else. That simple. It's the one thing Microsoft did right with IE. – Jimbo Jonny Oct 22 '15 at 02:20
  • Just two more months before we can dance on IE8's grave... hopefully it's just a few years before we can all ditch IE support altogether... – Michael Scheper Nov 19 '15 at 09:55

37 Answers37

357

This is my preferred way of doing it. It gives maximum control. (Note: Conditional statements are only supported in IE5 - 9.)

First set up your ie classes correctly

<!DOCTYPE html>
<!--[if lt IE 7]> <html class="lt-ie9 lt-ie8 lt-ie7"> <![endif]-->
<!--[if IE 7]>    <html class="lt-ie9 lt-ie8"> <![endif]-->
<!--[if IE 8]>    <html class="lt-ie9"> <![endif]-->
<!--[if gt IE 8]><!--> <html> <!--<![endif]-->    
<head>

Then you can just use CSS to make style exceptions, or, if you require, you can add some simple JavaScript:

(function ($) {
    "use strict";

    // Detecting IE
    var oldIE;
    if ($('html').is('.lt-ie7, .lt-ie8, .lt-ie9')) {
        oldIE = true;
    }

    if (oldIE) {
        // Here's your JS for IE..
    } else {
        // ..And here's the full-fat code for everyone else
    }

}(jQuery));

Thanks to Paul Irish.

Chris Halcrow
  • 21,541
  • 11
  • 115
  • 145
Jezen Thomas
  • 13,004
  • 5
  • 49
  • 87
  • 21
    Given that the OP asked for a purely JavaScript solution, I believe that the answer by @Tim Down below is better, as it doesn't involve changing the existing HTML, plus it's not using jQuery: http://stackoverflow.com/a/10965203/134120 – AsGoodAsItGets Jan 13 '15 at 10:53
  • I get an error with this on w3 html validator: `Error: Saw – abumalick Jun 22 '16 at 08:29
161

Return IE version or if not IE return false

function isIE () {
  var myNav = navigator.userAgent.toLowerCase();
  return (myNav.indexOf('msie') != -1) ? parseInt(myNav.split('msie')[1]) : false;
}

Example:

if (isIE () == 8) {
 // IE8 code
} else {
 // Other versions IE or not IE
}

or

if (isIE () && isIE () < 9) {
 // is IE version less than 9
} else {
 // is IE 9 and later or not IE
}

or

if (isIE()) {
 // is IE
} else {
 // Other browser
}
DBS
  • 6,536
  • 3
  • 28
  • 46
weroro
  • 1,665
  • 1
  • 11
  • 9
  • 37
    Doesn't work for IE11. From IE 11, they have changed the UA string to `"mozilla/5.0 (windows nt 6.3; wow64; trident/7.0; .net4.0e; .net4.0c; media center pc 6.0; .net clr 3.5.30729; .net clr 2.0.50727; .net clr 3.0.30729; rv:11.0) like gecko"` – Annie Jul 04 '13 at 12:22
  • 22
    Please note that in FF "false < 9" is "true". So, condition should be `if (isIE () && isIE () < 9) {` – nZeus Sep 08 '13 at 10:53
  • ie 10 was kicking out a 7. – DeadlyChambers Nov 07 '13 at 18:50
  • 3
    @DeadlyChambers perhaps it was running in IE7 standards mode? http://msdn.microsoft.com/en-us/library/ie/cc196988(v=vs.85).aspx – mason81 Nov 19 '13 at 22:35
  • 4
    The approved answer is how to detect IE version in HTML. This answers the original question. – Matt Wagner Jan 06 '15 at 21:56
  • Doesn't work for Microsoft Edge 38.xxx , return false – Prasad Gayan Jan 20 '17 at 06:38
  • 2
    @PrasadGayan - Microsoft Edge isn't Internet Explorer. So returning false seems to be the correct thing for it to do. – BryanGrezeszak Jun 09 '17 at 03:58
  • Thanks. just what I needed, and only for IE 8 and lower.. I realized that the usual conditional comments really didn't work for all cases, and needed a java script solution. Side note, I think I've wasted more time dealing with IE8 quirks than ANY other old browser I've tried to support. – Randy Dec 07 '20 at 16:37
117

If nobody else has added an addEventLister-method and you're using the correct browser mode then you could check for IE 8 or less with

if (window.attachEvent && !window.addEventListener) {
    // "bad" IE
}

Legacy Internet Explorer and attachEvent (MDN)

Community
  • 1
  • 1
Andreas
  • 19,756
  • 7
  • 41
  • 49
  • 7
    This seems like the most efficient way to detect IE <= 8 entirely in JavaScript - and is great for people like me who were looking for a way to do it. – Gregory Magarshak Mar 18 '13 at 15:33
  • Great! This also detects IE9 in Quirks Mode which is what I've been looking for. – sstur Apr 04 '14 at 18:40
  • 7
    Although this is an "easy to use" solution, it has some risks. Anyone in your company (that is not aware of your solution) can implement "addEventListener" or "attachEvent" to deal with the lack of it in IE 8. And then, your code will stop work. – Zé Carlos Jan 15 '15 at 16:08
116

Use conditional comments. You're trying to detect users of IE < 9 and conditional comments will work in those browsers; in other browsers (IE >= 10 and non-IE), the comments will be treated as normal HTML comments, which is what they are.

Example HTML:

<!--[if lt IE 9]>
WE DON'T LIKE YOUR BROWSER
<![endif]-->

You can also do this purely with script, if you need:

var div = document.createElement("div");
div.innerHTML = "<!--[if lt IE 9]><i></i><![endif]-->";
var isIeLessThan9 = (div.getElementsByTagName("i").length == 1);
if (isIeLessThan9) {
    alert("WE DON'T LIKE YOUR BROWSER");
}
Tim Down
  • 292,637
  • 67
  • 429
  • 506
  • 5
    The JavaScript version of @Tim Down's answer worked great for me. I used BrowserStack to test it with Windows 7 and IE 8, 9, 10 and 11; Mac OS X Snow Leopard with Safari 5.1, Firefox 28.0, Chrome 33.0 and Opera 20.0; iPhone 5 Mobile Safari; and Android Samsung Galaxy Tab 2 10.1 4.0. As expected, only IE8 reported that it was IeLessThan9. Nice! – Steve Saporta Mar 27 '14 at 20:52
60

To detect MSIE (v6 - v7 - v8 - v9 - v10 - v11) easily :

if (navigator.userAgent.indexOf('MSIE') !== -1 || navigator.appVersion.indexOf('Trident/') > 0) {
   // MSIE
}
EpokK
  • 37,670
  • 8
  • 57
  • 67
  • Useful for detecting IE10, since it does not support conditional comments. Does not work in IE11, but IE11 generally has an okay behavior – personne3000 Dec 13 '13 at 15:08
  • 11
    Finally an answer that doesn't lecture about using feature detection and actually answers the question. – cdmckay Jul 29 '14 at 23:45
32

Here is the way AngularJS checks for IE

/**
 * documentMode is an IE-only property
 * http://msdn.microsoft.com/en-us/library/ie/cc196988(v=vs.85).aspx
 */
var msie = document.documentMode;

if (msie < 9) {
    // code for IE < 9
}
iurii
  • 3,694
  • 2
  • 19
  • 26
  • Wow this is so much more simple than all the conditional commenting! No limitations of this? – andrewb Jul 24 '15 at 01:24
  • according to the docs, IE8+ supports this property so I think should be sufficient for most cases. – iurii Jul 24 '15 at 06:26
  • Per the MSDN reference, "When the current document has not yet been determined, documentMode returns a value of zero (0). This usually happens when a document is loading." Does this mean you might not get a valid response within a script loaded in ? – Erik Knowles Jul 30 '15 at 16:22
  • I think you can fix it by checking the value on window.onload when the document is already loaded. – iurii Jul 30 '15 at 18:27
28

To reliably filter IE8 and older, checking global objects can be used:

if (document.all && !document.addEventListener) {
    alert('IE8 or lower');
}
Marat Tanalin
  • 12,887
  • 1
  • 32
  • 50
Beaudinn Greve
  • 750
  • 10
  • 16
21

Detecting IE version using feature detection (IE6+, browsers prior to IE6 are detected as 6, returns null for non-IE browsers):

var ie = (function (){
    if (window.ActiveXObject === undefined) return null; //Not IE
    if (!window.XMLHttpRequest) return 6;
    if (!document.querySelector) return 7;
    if (!document.addEventListener) return 8;
    if (!window.atob) return 9;
    if (!document.__proto__) return 10;
    return 11;
})();

Edit: I've created a bower/npm repo for your convenience: ie-version

Update:

a more compact version can be written in one line as:

return window.ActiveXObject === undefined ? null : !window.XMLHttpRequest ? 6 : !document.querySelector ? 7 : !document.addEventListener ? 8 : !window.atob ? 9 : !document.__proto__ ? 10 : 11;
S.Serpooshan
  • 6,368
  • 2
  • 29
  • 53
Gabriel Llamas
  • 17,220
  • 24
  • 84
  • 105
16

This function will return the IE major version number as an integer, or undefined if the browser isn't Internet Explorer. This, like all user agent solutions, is suceptible to user agent spoofing (which has been an official feature of IE since version 8).

function getIEVersion() {
    var match = navigator.userAgent.match(/(?:MSIE |Trident\/.*; rv:)(\d+)/);
    return match ? parseInt(match[1]) : undefined;
}
Owen
  • 611
  • 6
  • 20
  • Owen, how does one use that in practice? How does one retrieve the return value? I tried `console.log(!!match && parseInt(match[1]))`, `console.log(parseInt(match[1]))` and `console.log(match)`, but no result with any of them. – Frank Conijn May 22 '14 at 04:55
  • Get the return value by calling the function itself `getIEVersion()`. For example: `if (getIEVersion() < 9) {/* IE 8 or below */}` `if (!getIEVersion()) {/* Not IE */}` – Owen May 23 '14 at 10:08
15

Detect IE in JS using conditional comments

// ----------------------------------------------------------
// A short snippet for detecting versions of IE in JavaScript
// without resorting to user-agent sniffing
// ----------------------------------------------------------
// If you're not in IE (or IE version is less than 5) then:
//     ie === undefined
// If you're in IE (>=5) then you can determine which version:
//     ie === 7; // IE7
// Thus, to detect IE:
//     if (ie) {}
// And to detect the version:
//     ie === 6 // IE6
//     ie > 7 // IE8, IE9 ...
//     ie < 9 // Anything less than IE9
// ----------------------------------------------------------

// UPDATE: Now using Live NodeList idea from @jdalton

var ie = (function(){

    var undef,
        v = 3,
        div = document.createElement('div'),
        all = div.getElementsByTagName('i');

    while (
        div.innerHTML = '<!--[if gt IE ' + (++v) + ']><i></i><![endif]-->',
        all[0]
    );

    return v > 4 ? v : undef;

}());
jKey
  • 183
  • 3
  • 8
  • That's pretty much the same as my answer. – Tim Down Aug 21 '13 at 17:49
  • @TimDown: Perhaps, but this answer is a little more feature-complete (it tells you the version number), and is well-commented. In addition, the link at the beginning of this answer leads to a Gist with several informative comments and interesting variations on this technique. – Alan Jan 10 '14 at 01:16
  • @Alan: Fair points. I tailored mine to the question but didn't cite the source. – Tim Down Jan 10 '14 at 09:34
12

This works for me. I use it as a redirect to a page that explains why we don't like < IE9 and provide links to browsers we prefer.

<!--[if lt IE 9]>
<meta http-equiv="refresh" content="0;URL=http://google.com">
<![endif]-->
iconMatrix
  • 173
  • 1
  • 2
  • 9
  • 1
    Ohw, that's a nasty one. I use a more friendly method, display a div with the looks of a IE warning and when visitor click on it the user goes to http://browsehappy.com – Codebeat Apr 07 '15 at 23:56
10

Your code can do the check, but as you thought, if someone try to access your page using IE v1 or > v19 will not get the error, so might be more safely do the check with Regex expression like this code below:

var userAgent = navigator.userAgent.toLowerCase();
// Test if the browser is IE and check the version number is lower than 9
if (/msie/.test(userAgent) && 
    parseFloat((userAgent.match(/.*(?:rv|ie)[\/: ](.+?)([ \);]|$)/) || [])[1]) < 9) {
  // Navigate to error page
}
Fong-Wan Chau
  • 2,080
  • 3
  • 22
  • 42
8

Conditional comments are no longer supported in IE as of Version 10 as noted on the Microsoft reference page.

var ieDetector = function() {
  var browser = { // browser object

      verIE: null,
      docModeIE: null,
      verIEtrue: null,
      verIE_ua: null

    },
    tmp;

  tmp = document.documentMode;
  try {
    document.documentMode = "";
  } catch (e) {};

  browser.isIE = typeof document.documentMode == "number" || eval("/*@cc_on!@*/!1");
  try {
    document.documentMode = tmp;
  } catch (e) {};

  // We only let IE run this code.
  if (browser.isIE) {
    browser.verIE_ua =
      (/^(?:.*?[^a-zA-Z])??(?:MSIE|rv\s*\:)\s*(\d+\.?\d*)/i).test(navigator.userAgent || "") ?
      parseFloat(RegExp.$1, 10) : null;

    var e, verTrueFloat, x,
      obj = document.createElement("div"),

      CLASSID = [
        "{45EA75A0-A269-11D1-B5BF-0000F8051515}", // Internet Explorer Help
        "{3AF36230-A269-11D1-B5BF-0000F8051515}", // Offline Browsing Pack
        "{89820200-ECBD-11CF-8B85-00AA005B4383}"
      ];

    try {
      obj.style.behavior = "url(#default#clientcaps)"
    } catch (e) {};

    for (x = 0; x < CLASSID.length; x++) {
      try {
        browser.verIEtrue = obj.getComponentVersion(CLASSID[x], "componentid").replace(/,/g, ".");
      } catch (e) {};

      if (browser.verIEtrue) break;

    };
    verTrueFloat = parseFloat(browser.verIEtrue || "0", 10);
    browser.docModeIE = document.documentMode ||
      ((/back/i).test(document.compatMode || "") ? 5 : verTrueFloat) ||
      browser.verIE_ua;
    browser.verIE = verTrueFloat || browser.docModeIE;
  };

  return {
    isIE: browser.isIE,
    Version: browser.verIE
  };

}();

document.write('isIE: ' + ieDetector.isIE + "<br />");
document.write('IE Version Number: ' + ieDetector.Version);

then use:

if((ieDetector.isIE) && (ieDetector.Version <= 9))
{

}
k0pernikus
  • 41,137
  • 49
  • 170
  • 286
Arnold.Krumins
  • 905
  • 7
  • 8
  • 1
    This was the only thing that worked on the entire net, at least the humongus of things i tried...thx ;) – Henrique C. Dec 10 '14 at 12:28
  • This code is good, but can't detect compability view mode. I'm on IE 11 using compability view in IE 8 and this code still giving `version 11` EDIT: This code is AMAZING! haha, it gives an object with everything inside. Version is 11 but docModeIR equals 9. Thanks! – MarceloBarbosa Feb 11 '15 at 17:42
5

For ie 10 and 11:

You can use js and add a class in html to maintain the standard of conditional comments:

  var ua = navigator.userAgent,
      doc = document.documentElement;

  if ((ua.match(/MSIE 10.0/i))) {
    doc.className = doc.className + " ie10";

  } else if((ua.match(/rv:11.0/i))){
    doc.className = doc.className + " ie11";
  }

Or use a lib like bowser:

https://github.com/ded/bowser

Or modernizr for feature detection:

http://modernizr.com/

Community
  • 1
  • 1
Liko
  • 1,910
  • 17
  • 19
  • 2
    I tried a few scripts and solutions but nothing worked. Then i included bowser in the project and it just worked. So one up for suggesting bowser. – Moulde Jan 19 '15 at 12:37
4

This has been answered to death, but this is all you need.

!!navigator.userAgent.match(/msie\s[5-8]/i)
Timothy Perez
  • 19,072
  • 7
  • 46
  • 39
3

To detect Internet Explorer 10|11 you can use this little script immediatelly after body tag:

In my case i use jQuery library loaded in head.

<!DOCTYPE HTML>
<html>
<head>
    <script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
</head>
<body>
    <script>if (navigator.appVersion.indexOf('Trident/') != -1) $("body").addClass("ie10");</script>
</body>
</html>
Brian
  • 61
  • 2
2
var Browser = new function () {
    var self = this;
    var nav = navigator.userAgent.toLowerCase();
    if (nav.indexOf('msie') != -1) {
        self.ie = {
            version: toFloat(nav.split('msie')[1])
        };
    };
};


if(Browser.ie && Browser.ie.version > 9)
{
    // do something
}
Berezh
  • 871
  • 8
  • 12
2

According to Microsoft, following is the best solution, it is also very simple:

function getInternetExplorerVersion()
// Returns the version of Internet Explorer or a -1
// (indicating the use of another browser).
{
    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;
}

function checkVersion()
{
    var msg = "You're not using Internet Explorer.";
    var ver = getInternetExplorerVersion();

    if ( ver > -1 )
    {
        if ( ver >= 8.0 ) 
            msg = "You're using a recent copy of Internet Explorer."
        else
            msg = "You should upgrade your copy of Internet Explorer.";
      }
    alert( msg );
}
AHH
  • 902
  • 2
  • 9
  • 22
  • Indeed, and just in case someone else lands here trying to use the above, the code in a later answer does work for IE11 ( https://stackoverflow.com/a/26375930/1129926). But beware, will it work for IE12, etc.? Bottom line is its best to consider these as temporary hacks and they are likely to fail later as new browser versions get released (I won't even mention Edge). – Jeff Mergler Apr 02 '18 at 21:17
1

I'm going to recommend not rewriting this code for the umpteenth time. I would recommend you use the Conditionizr library (http://conditionizr.com/) which is capable of testing for specific IE versions as well as other browsers, operating systems, and even the presence or absence of Retina displays.

Include the code for only the specific tests you need and you also gain the benefit of a tested library which has been through many iterations (and which would be easy to upgrade without breaking your code).

It also meshes nicely with Modernizr which can handle all of those cases where you are better off testing for a specific capability rather than a specific browser.

John Munsch
  • 19,481
  • 8
  • 40
  • 72
1

I do like that:

<script>
   function isIE () {
       var myNav = navigator.userAgent.toLowerCase();
       return (myNav.indexOf('msie') != -1) ? parseInt(myNav.split('msie')[1]) : false;
   }    
   var ua = window.navigator.userAgent;
   //Internet Explorer | if | 9-11

   if (isIE () == 9) {
       alert("Shut down this junk! | IE 9");
   } else if (isIE () == 10){
       alert("Shut down this junk! | IE 10");
   } else if (ua.indexOf("Trident/7.0") > 0) {
       alert("Shut down this junk! | IE 11");
   }else{
       alert("Thank god it's not IE!");
   }

</script>
1

This approach to detecting IE combines the strengths and avoids the weaknesses of jKey's answer using conditional comments and Owen's answer using user agents.

  • jKey's approach works up to version 9 and immune to user agent spoofing in IE 8 & 9.
  • Owen's approach can fail on IE 5 & 6 (reporting 7) and is susceptible to UA spoofing, but it can detect IE versions >= 10 (now also including 12, which postdates Owen's answer).

    // ----------------------------------------------------------
    // A short snippet for detecting versions of IE
    // ----------------------------------------------------------
    // If you're not in IE (or IE version is less than 5) then:
    //     ie === undefined
    // Thus, to detect IE:
    //     if (ie) {}
    // And to detect the version:
    //     ie === 6 // IE6
    //     ie > 7 // IE8, IE9 ...
    // ----------------------------------------------------------
    var ie = (function(){
        var v = 3,
            div = document.createElement('div'),
            all = div.getElementsByTagName('i');
    
        while (
            div.innerHTML = '<!--[if gt IE ' + (++v) + ']><i></i><![endif]-->',
            all[0]
        );
        if (v <= 4) { // Check for IE>9 using user agent
            var match = navigator.userAgent.match(/(?:MSIE |Trident\/.*; rv:|Edge\/)(\d+)/);
            v = match ? parseInt(match[1]) : undefined;
        }
        return v;
    }());
    

This can be used to set useful classes to your document containing the IE version:

    if (ie) {
        document.documentElement.className += ' ie' + ie;
        if (ie < 9)
            document.documentElement.className += ' ieLT9';
    }

Note that it detects the compatibility mode being used, if IE is in compatability mode. Also note that IE version is mostly useful for older versions (<10); higher versions are more standards-compliant and it's probably better to instead check for features using something like modernizr.js.

jtbr
  • 951
  • 10
  • 13
1

I made a convenient underscore mixin for this.

_.isIE();        // Any version of IE?
_.isIE(9);       // IE 9?
_.isIE([7,8,9]); // IE 7, 8 or 9?

_.mixin({
  isIE: function(mixed) {
    if (_.isUndefined(mixed)) {
      mixed = [7, 8, 9, 10, 11];
    } else if (_.isNumber(mixed)) {
      mixed = [mixed];
    }
    for (var j = 0; j < mixed.length; j++) {
      var re;
      switch (mixed[j]) {
        case 11:
          re = /Trident.*rv\:11\./g;
          break;
        case 10:
          re = /MSIE\s10\./g;
          break;
        case 9:
          re = /MSIE\s9\./g;
          break;
        case 8:
          re = /MSIE\s8\./g;
          break;
        case 7:
          re = /MSIE\s7\./g;
          break;
      }

      if (!!window.navigator.userAgent.match(re)) {
        return true;
      }
    }

    return false;
  }
});

console.log(_.isIE());
console.log(_.isIE([7, 8, 9]));
console.log(_.isIE(11));
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
danrichards
  • 153
  • 2
  • 3
1

or simply

//   IE 10: ua = 'Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; Trident/6.0)'; 
//   IE 11: ua = 'Mozilla/5.0 (Windows NT 6.3; Trident/7.0; rv:11.0) like Gecko'; 
// Edge 12: ua = 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.71 Safari/537.36 Edge/12.0'; 
// Edge 13: ua = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2486.0 Safari/537.36 Edge/13.10586'; 

var isIE = navigator.userAgent.match(/MSIE|Trident|Edge/)
var IEVersion = ((navigator.userAgent.match(/(?:MSIE |Trident.*rv:|Edge\/)(\d+(\.\d+)?)/)) || []) [1]
Giacomo
  • 94
  • 6
0

The most comprehensive JS script I found to check for versions of IE is http://www.pinlady.net/PluginDetect/IE/. The entire library is at http://www.pinlady.net/PluginDetect/Browsers/.

With IE10, conditional statements are no longer supported.

With IE11, the user agent no longer contains MSIE. Also, using the user agent is not reliable because that can be modified.

Using the PluginDetect JS script, you can detect for IE and detect the exact versions by using very specific and well-crafted code that targets specific IE versions. This is very useful when you care exactly what version of browser you are working with.

PressingOnAlways
  • 10,144
  • 4
  • 27
  • 48
0

I realise I am a little late to the party here, but I had been checking out a simple one line way to provide feedback on whether a browser is IE and what version from 10 down it was. I haven't coded this for version 11, so perhaps a little amendment will be needed for that.

However this is the code, it works as an object that has a property and a method and relies on object detection rather than scraping the navigator object (which is massively flawed as it can be spoofed).

var isIE = { browser:/*@cc_on!@*/false, detectedVersion: function () { return (typeof window.atob !== "undefined") ? 10 : (typeof document.addEventListener !== "undefined") ? 9 : (typeof document.querySelector !== "undefined") ? 8 : (typeof window.XMLHttpRequest !== "undefined") ? 7 : (typeof document.compatMode !== "undefined") ? 6 : 5; } };

The usage is isIE.browser a property that returns a boolean and relies on conditional comments the method isIE.detectedVersion() which returns a number between 5 and 10. I am making the assumption that anything lower than 6 and you are in serious old school territory and you will something more beefy than a one liner and anything higher than 10 and you are in to newer territory. I have read something about IE11 not supporting conditional comments but I've not fully investigated, that is maybe for a later date.

Anyway, as it is, and for a one liner, it will cover the basics of IE browser and version detection. It's far from perfect, but it is small and easily amended.

Just for reference, and if anyone is in any doubt on how to actually implement this then the following conditional should help.

var isIE = { browser:/*@cc_on!@*/false, detectedVersion: function () { return (typeof window.atob !== "undefined") ? 10 : (typeof document.addEventListener !== "undefined") ? 9 : (typeof document.querySelector !== "undefined") ? 8 : (typeof window.XMLHttpRequest !== "undefined") ? 7 : (typeof document.compatMode !== "undefined") ? 6 : 5; } };

/* testing IE */

if (isIE.browser) {
  alert("This is an IE browser, with a detected version of : " + isIE.detectedVersion());
}
Ric
  • 640
  • 5
  • 10
0

Detecting IE and its versions couldn't be easier, and all you need is a bit of native/vanilla Javascript:

var uA = navigator.userAgent;
var browser = null;
var ieVersion = null;

if (uA.indexOf('MSIE 6') >= 0) {
    browser = 'IE';
    ieVersion = 6;
}
if (uA.indexOf('MSIE 7') >= 0) {
    browser = 'IE';
    ieVersion = 7;
}
if (document.documentMode) { // as of IE8
    browser = 'IE';
    ieVersion = document.documentMode;
}

And this is a way to use it:

if (browser == 'IE' && ieVersion <= 9) 
    document.documentElement.className += ' ie9-';

.

Works in all IE versions, including higher versions in lower Compatability View/Mode, and documentMode is IE proprietary.

Frank Conijn
  • 2,627
  • 19
  • 28
0

If you need to delect IE Browser version then you can follow below code. This code working well for version IE6 to IE11

<!DOCTYPE html>
<html>
<body>

<p>Click on Try button to check IE Browser version.</p>

<button onclick="getInternetExplorerVersion()">Try it</button>

<p id="demo"></p>

<script>
function getInternetExplorerVersion() {
   var ua = window.navigator.userAgent;
        var msie = ua.indexOf("MSIE ");
        var rv = -1;

        if (msie > 0 || !!navigator.userAgent.match(/Trident.*rv\:11\./))      // If Internet Explorer, return version number
        {               
            if (isNaN(parseInt(ua.substring(msie + 5, ua.indexOf(".", msie))))) {
                //For IE 11 >
                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);
                        alert(rv);
                    }
                }
                else {
                    alert('otherbrowser');
                }
            }
            else {
                //For < IE11
                alert(parseInt(ua.substring(msie + 5, ua.indexOf(".", msie))));
            }
            return false;
        }}
</script>

</body>
</html>
Nimesh
  • 2,684
  • 1
  • 24
  • 30
0

Window runs IE10 will be auto update to IE11+ and will be standardized W3C

Nowaday, we don't need to support IE8-

    <!DOCTYPE html>
    <!--[if lt IE 9]><html class="ie ie8"><![endif]-->
    <!--[if IE 9]><html class="ie ie9"><![endif]-->
    <!--[if (gt IE 9)|!(IE)]><!--><html><!--<![endif]-->
    <head>
        ...
        <!--[if lt IE 8]><meta http-equiv="Refresh" content="0;url=/error-browser.html"><![endif]--
        ...
    </head>
xicooc
  • 787
  • 6
  • 8
0
var isIE9OrBelow = function()
{
   return /MSIE\s/.test(navigator.userAgent) && parseFloat(navigator.appVersion.split("MSIE")[1]) < 10;
}
xicooc
  • 787
  • 6
  • 8
0
if (!document.addEventListener) {
    // ie8
} else if (!window.btoa) {
    // ie9
}
// others
Bruce
  • 2,036
  • 2
  • 23
  • 20
0
// Detect ie <= 10
var ie = /MSIE ([0-9]+)/g.exec(window.navigator.userAgent)[1] || undefined;

console.log(ie);
// Return version ie or undefined if not ie or ie > 10
Liberateur
  • 799
  • 1
  • 9
  • 31
0

The below codepen identifies IE version in all cases (IE<=9, IE10, IE11 and IE/Edge)

function detectIE() {
    var ua = window.navigator.userAgent;
    var msie = ua.indexOf('MSIE ');
    if (msie > 0) {
        // IE 10 or older => return version number
        return parseInt(ua.substring(msie + 5, ua.indexOf('.', msie)), 10);
    }
    var trident = ua.indexOf('Trident/');
    if (trident > 0) {
        // IE 11 => return version number
        var rv = ua.indexOf('rv:');
        return parseInt(ua.substring(rv + 3, ua.indexOf('.', rv)), 10);
    }
    var edge = ua.indexOf('Edge/');
    if (edge > 0) {
        // Edge (IE 12+) => return version number
        return parseInt(ua.substring(edge + 5, ua.indexOf('.', edge)), 10);
    }
    // other browser
    return false;
}

ref: https://codepen.io/gapcode/pen/vEJNZN

jeetaz
  • 641
  • 1
  • 5
  • 10
0

Don't over complicate such simple things. Just use a plain and simple JScript conditional comment. It is the fastest because it adds zero code to non-IE browsers for the detection, and it has compatibility dating back to versions of IE before HTML conditional comments were supported. In short,

var IE_version=(-1/*@cc_on,@_jscript_version@*/);

Beware of minifiers: most (if not all) will mistake the special conditional comment for a regular comment, and remove it

Basically, then above code sets the value of IE_version to the version of IE you are using, or -1 f you are not using IE. A live demonstration:

var IE_version=(-1/*@cc_on,@_jscript_version@*/);
if (IE_version!==-1){
    document.write("<h1>You are using Internet Explorer " + IE_version + "</h1>");
} else {
    document.write("<h1>You are not using a version of Internet Explorer less than 11</h1>");
}

This works based on the fact that conditional comments are only visible in older versions of Internet Explorer, and IE sets @_jscript_version to the version of the browser. For example, if you are using Internet Explorer 7, then @_jscript_version will be set to 7, thus, the postprocessed javascript that will be executed will actually look like this:

var IE_version=(-1,7);

which gets evaluated to 7.

0

It helped me

function IsIE8Browser() {
  var rv = -1;
  var ua = navigator.userAgent;
  var re = new RegExp("Trident\/([0-9]{1,}[\.0-9]{0,})");
  if (re.exec(ua) != null) {
    rv = parseFloat(RegExp.$1);
  }
  return (rv == 4);
}
Pablo
  • 436
  • 3
  • 12
0
function getIEVersion(){
     if (/MSIE |Trident\//.test( navigator.userAgent )=== false) return -1;
    /**[IE <=9]*/
    var isIE9L = typeof ( window.attachEvent ) === 'function' && !( Object.prototype.toString.call( window.opera ) == '[object Opera]' ) ? true : false;
    var re;
    if(isIE9L){
        re = new RegExp( "MSIE ([0-9]{1,}[\.0-9]{0,})" );
        if(re.exec( navigator.userAgent ) !== null)
            return parseFloat( RegExp.$1 );
        return -1;
    }
    /**[/IE <=9]*/
    /** [IE >= 10]*/
    if(navigator.userAgent.indexOf( 'Trident/' ) > -1){
        re = new RegExp( "rv:([0-9]{1,}[\.0-9]{0,})" );
        if(re.exec( navigator.userAgent ) !== null)
            return parseFloat( RegExp.$1 );
        return -1;
    }
    /**[/IE >= 10]*/
    return -1;
};

Check here ==>

var ieVersion = getIEVersion();

if(ieVersion < 0){
    //Not IE
}
//A version of IE

Learn more about browser navigator https://developer.mozilla.org/en-US/docs/Web/API/Window/navigator

rktuxyn
  • 593
  • 9
  • 18
-1

Using JQuery:

http://tanalin.com/en/articles/ie-version-js/

Using C#:

var browser = Request.Browser.Browser;
Vojtěch Dohnal
  • 7,154
  • 2
  • 36
  • 91
-1

Simple solution stop thinking browser and use the year.

var year = eval(today.getYear());
if(year < 1900 )
 {alert('Good to go: All browsers and IE 9 & >');}
else
 {alert('Get with it and upgrade your IE to 9 or >');}