17

Hello I want to detect the Browser , IE 8 or more will be appropriate for me. For this i used following code but it fails for IE 11 . For other its detecting properly.

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;
}

Below is the link which also I tried but couldn't succeed.

Spudley
  • 166,037
  • 39
  • 233
  • 307
Abhinash Mohanty
  • 183
  • 1
  • 1
  • 4
  • 7
    **DO NOT DO BROWSER DETECTION!** It will break, and it will cause you problems. – Spudley Sep 18 '13 at 12:04
  • 1
    Aside to avoid browser detection, check this http://msdn.microsoft.com/en-us/library/ie/bg182625(v=vs.85).aspx – Irvin Dominin Sep 18 '13 at 12:12
  • 7
    How about you let us detect defective versions of IE if we want to? This is the real world, just answer the question. – mpowered Feb 28 '14 at 01:07
  • We sometimes NEED to DO BROWSER DETECTION :-) : I known my intranet WebSite is compatible neither with IE6 nor "IE11 compatible mode". And I want to display a warning message in these cases. It's hard because when compatible mode is "On", the "IE11 compatible mode" could be detected as IE7... – Elo Dec 10 '14 at 09:37

10 Answers10

54

You can explicitly detect IE11 with the following check (using feature detection):

if (Object.hasOwnProperty.call(window, "ActiveXObject") && !window.ActiveXObject) {
    // is IE11
}

Explanation: All versions of IE (except really old ones) have window.ActiveXObject property present. IE11, however hides this property from DOM and that property is now undefined. But the property itself is present within object, so checking for property presence returns true in all IE versions, but in IE11 it also returns false for second check. And, finally, hasOwnProperty is called via Object because in IE8 (and I believe earlier) window is not an instanceof Object and does not have hasOwnProperty method.

Another method, using userAgent string:

var ua = window.navigator.userAgent;
var versionSplit = /[\/\.]/i;
var versionRe = /(Version)\/([\w.\/]+)/i; // match for browser version
var operaRe = /(Opera|OPR)[\/ ]([\w.\/]+)/i;
var ieRe = /(?:(MSIE) |(Trident)\/.+rv:)([\w.]+)/i; // must not contain 'Opera'
var match = ua.match(operaRe) || ua.match(ieRe);
if (!match) {
    return false;
}
if (Array.prototype.filter) {
    match = match.filter(function(item) {
        return (item != null);
    });
} else {
    // Hello, IE8!
    for (var j = 0; j < match.length; j++) {
        var matchGroup = match[j];
        if (matchGroup == null || matchGroup == '') {
            match.splice(j, 1);
            j--;
        }
    }
}
var name = match[1].replace('Trident', 'MSIE').replace('OPR', 'Opera');
var versionMatch = ua.match(versionRe) || match;
var version = versionMatch[2].split(versionSplit);

This will detect any version of IE if its userAgent string was not spoofed.

There very rare cases when you actually need to use browser detection as described above. In most cases feature detection approach is preferable.

Mesqalito
  • 669
  • 5
  • 6
13
 isIE11 = !!window.MSStream;

 if(isIE11){
   /* Something */
 }
12

Use !(window.ActiveXObject) && "ActiveXObject" in window to detect IE11 explicitly.

To detect any IE version, use window.ActiveXObject || "ActiveXObject" in window instead.

mcw
  • 3,500
  • 1
  • 31
  • 33
  • I use `(navigator.userAgent.search("MSIE") >= 0) || (!(window.ActiveXObject) && "ActiveXObject" in window)`, thanks for help – Szymon Toda Dec 07 '13 at 19:34
  • As mentioned in the accepted answer, doing browser detection by reading the userAgent string is brittle and not recommended. Microsoft specifically changed the UA string in IE11 to break this. Also, there are features in IE that allow it to change the UA string being transmitted. So, again - use feature detection instead. – mcw Dec 09 '13 at 23:05
  • 1
    in your second line `window.ActiveXObject || "ActiveXObject" in window` the first part is redundant. – Royi Namir Dec 16 '13 at 10:51
  • 1
    Thanks for this. Exactly what I needed. Also seems to cope with emulating lower browsers through the F12 dev tools. User-agent-string didn't seem to change when emulating IE8 from IE11 for example... – El Ronnoco Dec 05 '14 at 11:39
5

As already stated - dont do browser detection, rather do feature detection. However as I see your script is an older version of a script the circulates around here. This is the updated version that detects IE 11 aswel:

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;
                            }
Tsonev
  • 435
  • 7
  • 17
3

Is better for you if you avoid browser detection; if you need it here is a good explain from MS team:

In rare cases, it may be necessary to uniquely identify IE11 Preview. Use the Trident token to do so

User-agent string changes

For many legacy websites, some of the most visible updates for IE11 Preview involve the user-agent string. Here's what's reported for IE11 Preview on Windows 8.1 Preview: JavaScript

Mozilla/5.0 (Windows NT 6.3; Trident/7.0; rv:11.0) like Gecko

As with previous versions of Internet Explorer, portions of user-agent string vary according to the environment. Here's the string for IE11 Preview on Windows 7: JavaScript

Mozilla/5.0 (Windows NT 6.1; Trident/7.0; rv:11.0) like Gecko

If you compare these strings to the ones reported by earlier versions of Internet Explorer, you'll find the following changes: The compatible ("compatible") and browser ("MSIE") tokens have been removed. The "like Gecko" token has been added (for consistency with other browsers). The version of the browser is now reported by a new revision ("rv") token. These changes help prevent IE11 Preview from being (incorrectly) identified as an earlier version. In general, you should avoid detecting specific browsers or browser versions. The assumptions underlying such tests tend to lead to false positive results when browsers are updated. Instead, detect features as you need them and use progressive enhancement to provide simplified experiences for browsers or devices that do not support the features you need. In rare cases, it may be necessary to uniquely identify IE11 Preview. Use the Trident token to do so

Link: http://msdn.microsoft.com/en-us/library/ie/bg182625(v=vs.85).aspx

Irvin Dominin
  • 30,819
  • 9
  • 77
  • 111
1

More easy and efficient code and detect all versions of IE/Edge:

if(navigator.appVersion.indexOf("MSIE") != -1 || navigator.appVersion.indexOf("Trident") != -1 || navigator.appVersion.indexOf("Edge") != -1){
// is IE
}
Serginho
  • 7,291
  • 2
  • 27
  • 52
0

I used the following code recently to detect IE in general and it worked just fine for IE 11 as well

var bs = document.body.style, isIE=false;
if ('msTransition' in bs) {
        isIE = true;
}

The idea is to look for vedor prefix.

0

The 'use feature detection' mantra mystifies me. When you hit a bug, how can you determine what 'feature' is the culprit? Take for example this bit of code:

        $('input[name^=qty]').keyup(function(e) {
            if (this.value.match(/[^0-9\/]*/g)) {
                this.value = this.value.replace(/[^0-9\/]/g, '')
            }
        });

It removes non-numeric chars from the input field as the user types. Works in FF, Chrome, and Safari. Does not work in ANY version of IE (up to 11, at least): any subsequent bindings on the input field will fail.

Jeff Lowery
  • 2,492
  • 2
  • 32
  • 40
-1

feature detect, feature detect, feature detect

        <script>

    if (!('querySelector' in document)  //this should work in ie 9+
         || !('localStorage' in window)  //ie 8+
         || !('addEventListener' in window)  //ie 8 + (I think)
        || !('matchMedia' in window)) {//ie 10+

        //do your redirect here
    }

</script>
Chris Love
  • 3,740
  • 1
  • 19
  • 16
  • 2
    This is not what's meant by the mantra of use feature detection. This is just a different path to user agent detection... the features are really an "alias" for what the user agent is. "Use feature detection" means that if you need a certain feature, detect it... and provide fallbacks when requirements demand it. – Greg Pettit Apr 21 '14 at 13:59
  • I disagree. The comments are only meant as mental placeholders. This is feature detection I use to either create a modern SPA client experience or redirect to a 'core' site that is just some basic CSS with classic server rendered markup. – Chris Love Apr 22 '14 at 13:09
-10

DO NOT DO BROWSER DETECTION! It will break, and it will cause you problems.

IE11 has a completely different User Agent string to previous IE versions; it not longer includes the "MSIE" text. This is why your detection code doesn't work.

It's important to note here that the reason they did this was deliberate. They wanted to break browser detection scripts like this.

It is possible to change your code to work with IE11, but I strongly recommend not doing this, as you'll probably have the same issue all over again when IE12 comes out.

So why did they want to break browser detection scripts? Simple: Because IE11 does not have the bugs of previous versions, and it has a lot of new features. So if you're doing browser detection because IE has certain bugs or missing features and you've got code to fix those issues based on the browser detect, then that code might actually cause worse problems in IE11 where the fixes aren't needed.

IE11 has broken your script, but the same logic applies to all browsers and all versions; detecting the browser and version is almost always the wrong thing to do.

If there are specific features that you want to support, but are missing in older IE versions (or other older browsers), don't use browser detection to work it out; you should use feature detection instead.

Feature detection means checking the browser to see whether it supports the particular features you want to use. The most common way of doing this is to use the Modernizr library. The docs on their site will guide you through setting it up.

There are a few bugs in older IE versions which are hard to detect, and for these few cases, it is valid to use browser detection as a last resort, but these cases are really only for IE6 and earlier. Maybe occasionally for IE7. But you've stated in the question that you're only looking at IE8 and later, so that should not apply.

Stick with feature detection; it's more reliable, better practice, and won't break suddenly when a new browser version is released.

Spudley
  • 166,037
  • 39
  • 233
  • 307
  • Hello Spudley,Thank you for your time.You are correct that we should go with feature detection rather than Browser version detection. I am facing the issue because our application is using ActiveX control present in IE to make an RDP connection in our web application.Now as it is a existed application, I am told just to check the IE version , which is failing in IE 11.Can I have a piece of code to check this feature(RDP connect) in IE or any way to validate the version of Browser ? As I dont want to do more changes to the existed app. Thanks. – Abhinash Mohanty Sep 19 '13 at 08:23
  • 1
    In most cases, you can detect whether a feature is available in the browser by saying `if(window.feature)` or something similar. For example, to detect whether activeX is available, use [`if(window.activeX)`](http://stackoverflow.com/questions/4313438/how-do-i-detect-if-activex-is-enabled-in-the-browser-of-client). Hope that helps. – Spudley Sep 19 '13 at 08:49
  • 2
    Hello, Thank you for the suggestion.Unfortunately the feature verification is also not working for IE 11. Below is my code. if (typeof (window.ActiveXObject) == "undefined") { alert("Not verified"); IsVerified = false; } else { alert("Verified"); IsVerified = true; } This works fine for all other browsers but for IE 11 its not working.Any suggestion will really appreciated. ?? – Abhinash Mohanty Sep 19 '13 at 10:10
  • When you say "it doesn't work in IE11", do you mean it gives "Not verified"? Maybe that's correct; maybe your IE11 has activeX disabled? (I think the standard config is for activex to be disabled) – Spudley Sep 19 '13 at 10:32
  • 1
    Thanks for the reply. I am now able to get rid of the problem. – Abhinash Mohanty Sep 19 '13 at 12:25
  • 23
    Your whole speach makes no sense and is out of scope of that question. I want check what browser user runs. Period. -1 – Szymon Toda Dec 07 '13 at 19:18
  • 7
    Yes IE11 has no bugs of previous versions, infect it has its own new collection of bugs. Mostly when you are using a javascript library like ExtJS etc :) I'm stucked from last four days trying to solve them – Raza Ahmed Dec 20 '13 at 07:03
  • 1
    @Ultra Good, sound advice > blindly answering questions. Why let someone create a problem for themselves or someone else down the road when you can tell them a better way to do it? – Micah Henning Jan 05 '14 at 06:33
  • 32
    HEY, GUESS WHAT?!? IE10/11 still have bugs. We still have ways to work around them. I think it's incredibly arrogant of them to say that their browser is perfect and that no one should use browser detection when some VERY basic features still just don't work. My use-case is for the broken implementation of input padding--IE just plain ignores it until you set the input to '' and back to your value. Not my fault that they can't make a proper browser. Please, please, PLEASE just answer the question without injecting your unnecessary opinion. – mpowered Jan 06 '14 at 20:34
  • 20
    -1 because this post does not attempt to answer the question. The OP was asking how to accomplish something, not whether or not that thing was the right move. – Kevin Laity Jan 31 '14 at 22:12
  • 2
    The ActiveXObject verifcation is now hidden - http://msdn.microsoft.com/en-us/library/ie/dn423948(v=vs.85).aspx. – Jarrod Feb 17 '14 at 18:10
  • 1
    Appreciate the context, but please do answer the question. – U007D Feb 24 '14 at 21:10
  • Absolutely positioned elements will be overlapped by IE's pdf plugin and require an iframe shim. There is no feature detection for that. "ActiveXObject" in window does the trick from 8-11. – ptrc Mar 13 '14 at 15:13
  • 2
    @Spudley - I don't mean any offense, but this is not sound advice. IE11 has just as many bugs (if not more) as IE10, they are just different. We can't detect bugs with feature detection, so guess what the only other solution is? Tell our clients to switch to Chrome. We have around 20,000 users of our product. In IE9 and IE10, we were able to work around the bugs by detecting the browser. With IE11, there's no such option ... so now our call center reps switch any IE11 users to Chrome (5,000+ migrations just since IE11 was released). I don't think Microsoft thought this one through. – Beep beep Apr 23 '14 at 17:01
  • 1
    @MicahHenning If we didn't need these hacks no-one would be asking for them. I've got a bug I'm attempting to work around right now where IE11, and only IE11 crashes if I attempt to read the innerText of a dynamically created span element after adding, then removing it from the page. I didn't want to change working behaviour on all other browsers just because IE is broken, but apparently that's the advice here, rewrite working code because IE is buggy but tries to pretend it's a real browser. Pretending IE11 is perfect doesn't solve it being a buggy excuse for a browser. – scragar Jul 10 '14 at 15:38
  • 1
    The question was clear, how to detect IE11. I'm in a situation where IE11 behaves in a different way then in chrome and the code needs to be forked to makes allowances which requires browser detection. -1 – Kywillis Jul 15 '14 at 18:11
  • @Kywillis: I disagree. Nothwithstanding the fact that the OP accepted the answer (so it obviously helped him?), in this question the OP wants a detection for IE8 and higher, including IE11. Not just IE11. It is really important to understand that there is virtually zero commonality between IE8 and IE11 in terms of browser bugs. Yes IE11 has bugs, but they are not the same ones that IE8 had. Using common detection code for them is futile and will lead to bugs in your own code. – Spudley Jul 16 '14 at 06:21
  • 2
    @Kywillis: Also, please don't use Chrome as a baseline that all browsers must conform to: Chrome has plenty of bugs and quirks of its own. Using it as an infallible benchmark is the same mistake we made with IE6 a decade ago. – Spudley Jul 16 '14 at 06:24
  • 1
    This is an arrogant and unhelpful answer and mentality. IE11 is not the rock-solid browser people claim it to be, and just like all past versions of IE, its faults are not a complete lack of support for modern features (which can easily be worked around through progressive enhancement) but faulty support of features that other browsers handle just fine (SVG in my case). And for the people complaining that Chrome is an inaccurate baseline for behavior: Chrome, Firefox, Safari, and Opera are all more or less on par for behavior and performance with only minor deviations in rendering. – cmal Aug 08 '14 at 19:03
  • 1
    Hi @Spudley, afraid I must pile on as well. My web site needs to display a tip to instruct the user how to set the page as their browser start page. These instructions will obviously be different for each browser. So I have a legit use case. – WolfRevokCats Aug 26 '14 at 05:51
  • @scragar What you're trying to accomplish is a bit unusual. Behavior outside the scope of the ECMAScript specification is entirely up to the browser. You may have to work around your implementation, which in my opinion is better than targeting a browser. Did you try .textContent? If I remember correctly, that's the proper way to get an Element's inner text. I think the attribute .innerText was an IE-specific implementation that goes against the spec. Some other browsers implemented it solely for compatibility reasons. Otherwise, try to get the content before you remove the element from DOM. – Micah Henning Sep 15 '14 at 20:28
  • As much as this may be the right answer to the X problem when the user was asking for Y, it's not an answer to Y, and it's nasty. Give more context to how they can accomplish Y as well as why they should be accomplishing X. – Shotgun Ninja May 14 '15 at 14:44
  • I am not gonna down-vote this post, but feature detection is useless. Unless they provide a bug-detection API which is what developers usually need (since all existing crap-browsers are flood-filled with bugs) people will continue to need to get the browser family and version. And that's pretty reasonable and fine with me. When you are in shit, you try to get out of it by any means... – user2173353 Oct 12 '15 at 08:03
  • We don't detect IE to fix their bugs. We detect IE to react accordingly. For example, downloading files in IE is different than other browsers. – Marble Daemon Jun 30 '16 at 02:53
  • @Spudley Many times I have run into rendering differences where I have to use browser detection to fix it. In that case you can't use feature detection! – TheStoryCoder Mar 19 '19 at 15:40
  • @TheStoryCoder (and to anyone else still reading / voting on this post): Please bear in mind that this answer was posted more than half a decade ago. The state of the web, of browser development, and the benefits of (and the need for) feature detection vs browser detection is completely different today to how it was back then. When I answered this question, a lot of sites were broken in Firefox and Chrome when they didn't need to be because of poor use of browser detection, where if they'd used feature detection they would work in all browsers. – Spudley Mar 19 '19 at 16:28
  • @Spudley, Funny part is that 6 years later and IE11 is still the primary browser for internal applications at many businesses. As other pointed out, Feature Detection works great for detecting features but not when dealing with Bugs. In my case it would be the weird implementation of z-order handling with iFrames that allows iFrames to pop over other content in IE. – AnthonyVO Jul 10 '19 at 20:31