488

I am calling a function like the one below by click on divs with a certain class.

Is there a way I can check when starting the function if a user is using Internet Explorer and abort / cancel it if they are using other browsers so that it only runs for IE users ? The users here would all be on IE8 or higher versions so I would not need to cover IE7 and lower versions.

If I could tell which browser they are using that would be great but is not required.

Example function:

$('.myClass').on('click', function(event)
{
    // my function
});
Daniel Tonon
  • 9,261
  • 5
  • 61
  • 64
user2571510
  • 11,167
  • 39
  • 92
  • 138
  • Here are a lot of examples: http://stackoverflow.com/questions/2400935/browser-detection-in-javascript – Reeno Nov 15 '13 at 11:00
  • 1
    Use modernizer to detect IE or other browsers. http://stackoverflow.com/questions/13478303/correct-way-to-use-modernizr-to-detect-ie – chris Nov 15 '13 at 11:05
  • Please note, with modern web development, it's bad practice to detect browsers. – Sameer Alibhai May 14 '15 at 19:40
  • 7
    By modern web development standards, it's bad practice to develop for old versions of IE to begin with. – Rosseyn Oct 08 '15 at 18:36
  • 11
    Actually, this "bad practice" is forced by the standards themselves, so it's not the developer's fault... Browsers work differently and and the specs are too soft on implementation issues. In order to make something that is not buggy and not boring as hell one *has* to do browser detection. I would suggest an other best practice: `With modern web development, it's bad practice to support non-Chromium-based browsers (with Safari not considered to be Chromium-based at all)`. Sorry, but this insanity must end at some point and somehow... – user2173353 Oct 29 '15 at 15:26
  • 3
    It is better practice today to do "feature detection" over "browser detection". Ask whether the browser does what you need instead. – Chris Rogers Nov 19 '15 at 04:39
  • 2
    @ChrisRogers - That sounds great and all, but if you need to add some inline styles because of a [bug in how IE measures the size of child elements of a flexbox element](http://stackoverflow.com/q/35073868/211627), then yeah... you need browser detection. – JDB Jan 28 '16 at 23:07
  • @JDB - Well.. erm.. yeah, of course. I don't think anyone's laying down absolute laws here. I still stand by the advice of what is *preferable*. What's more, the example given by the OP does not necessarily imply they are about to write a CSS hack. On the surface, it's appears reasonably likely that they are about to call some javascript function. – Chris Rogers Feb 02 '16 at 03:56
  • 2
    @Chris - apologies... meant for that to have more of a jokey tone. I'm going to blame IE for stealing my joy and leaving me with bitterness and frustration. :) – JDB Feb 02 '16 at 04:00
  • 2
    @JDB - no worries at all. IE (aka. "the moon faced assassin of joy") has extinguished many a soul. :-) – Chris Rogers Feb 02 '16 at 04:03
  • 1
    Build something cool! Does it work? No?! Here you go, it's an IE. – Jonathan Mar 06 '16 at 18:30
  • @Rosseyn By modern development standards, it's bad practice to use an application as bad as IE to begin with. Nevertheless, the pandemic that is IE is forever. As long as customers are too naive to use something else, our jobs depend on satisfying them despite the carnage that follows. – Suncat2000 May 04 '17 at 21:01
  • 1
    Can "with jQuery" be removed from the question title so it just says "Check if user is using IE"? The best answers in this thread don't require any jQuery and this is the first result in Google if you type "check if IE". Having jQuery in the title might drive some people away from the question. – Daniel Tonon Apr 11 '19 at 20:47
  • Forgot that I have edit permissions – Daniel Tonon Apr 11 '19 at 20:49

33 Answers33

723

It's several years later, and the Edge browser now uses Chromium as its rendering engine.
Checking for IE 11 is still a thing, sadly.

Here is a more straightforward approach, as ancient versions of IE should be gone.

if (window.document.documentMode) {
  // Do IE stuff
}

Here is my old answer (2014):

In Edge the User Agent String has changed.

/**
 * detect IEEdge
 * returns version of IE/Edge or false, if browser is not a Microsoft browser
 */
function detectIEEdge() {
    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 => return version number
       return parseInt(ua.substring(edge + 5, ua.indexOf('.', edge)), 10);
    }

    // other browser
    return false;
}

Sample usage:

alert('IEEdge ' + detectIEEdge());

Default string of IE 10:

Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; Trident/6.0)

Default string of IE 11:

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

Default string of Edge 12:

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 

Default string of Edge 13 (thx @DrCord):

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 

Default string of Edge 14:

Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2486.0 Safari/537.36 Edge/14.14300 

Default string of Edge 15:

Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.116 Safari/537.36 Edge/15.15063 

Default string of Edge 16:

Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36 Edge/16.16299 

Default string of Edge 17:

Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.140 Safari/537.36 Edge/17.17134 

Default string of Edge 18 (Insider preview):

Mozilla/5.0 (Windows NT 10.0; Win64; x64; ServiceUI 14) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.140 Safari/537.36 Edge/18.17730 

Test at CodePen:

http://codepen.io/gapcode/pen/vEJNZN

Mario
  • 8,253
  • 2
  • 14
  • 29
  • tested in IE 9 and it doesn't work as written. The problem is that "Trident" is now in the IE9 ua string and is formatted like this: ""Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.0; Trident/5.0; SLCC1; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; .NET4.0C; .NET4.0E)" so the parsing failed and NaN was returned. One fix is to make "if(trident" into "else if(trident". I've tested that on IE9 and IE11. I've taken your code & my changes and merged them into the answer over here http://stackoverflow.com/a/16657946/684852 also. – Sean Colombo Mar 06 '14 at 15:38
  • 4
    Thank you for commenting. I have not verified your answer yet, but I want to comment one thing: As the first 'if' contains a 'return', you don't need an 'else' afterwards. – Mario Mar 06 '14 at 16:15
  • But it gives the message "IE restricted this webpage from running scripts or Active X Controls". So i will have to get the users permission before doing anything? – Diffy Jun 27 '14 at 08:48
  • It will not work until the user allows the page to run scripts. Yes. – Mario Jun 27 '14 at 13:38
  • 33
    Just curious, why the heck do they change the user agent line in new versions of IE? MS seriously don't want us to detect their awful web browser. – c00000fd Feb 02 '15 at 09:16
  • @c00000fd Because they are building their new browser implementing web standards, detecting browser is a bad practice which should be abandoned. You should detect features instead. – Sameer Alibhai May 14 '15 at 19:34
  • 3
    @SameerAlibhai Which sounds good in theory but in practice, especially currently, it's not practical. Sometimes issues arise that a single "feature" detection doesn't encompass and plus certain features have implementation quirks that can only be worked around with knowledge of the browser. What if I want to do something simple like collect browser statistics? – Slight May 21 '15 at 20:39
  • 34
    It should be noted that Edge isn't really 'IE12' but is in fact a completely separate browser. Windows 10 comes with both IE11 and Edge installed. – moloko Sep 29 '15 at 18:32
  • Just a note: Edge on Windows 10 after an upgrade now reports this UA string `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` NOTE the 13 instead of 12 as the Edge version number! – DrCord Dec 16 '15 at 17:25
  • 1
    @snowYetis - they did get rid of IE, the new browser is now Edge and is much better. – DrCord Dec 16 '15 at 17:37
  • Thank you @DrCord, this will show IE 13 as result. It is covered by the current script. I updated the pen (CodePen) with a new test value. – Mario Dec 17 '15 at 16:44
  • @DrCord Edge is cool. I had to fix some controls at my job so they would render properly in Edge. It does not play well with Transform:Matrix. – snowYetis Dec 18 '15 at 02:20
  • 1
    Thanks a lot.Accepted answer returned NaN in IE 11 but your solution worked. – Bugfixer Sep 29 '16 at 07:02
  • @Mario: Thank you very much that you cared enough to create a test for your solution! That's very helpful for quick verification. – Ivo Mori Mar 16 '17 at 07:48
  • 3
    Edge is NOT Internet Explorer or IE12. Please stop implying this. Also, what is the point of detecting Edge? It's Chromium based, so you should also add Opera and Chrome to this code. – hda Dec 16 '18 at 17:26
  • @hda yes EDGE is Chromium based, so support all Chromium features? Just for this maybe want detect it. – BOZ Apr 21 '19 at 14:25
  • Where did this mis-information that Edge is Chromium based come from? That is so wrong and so bizzare. Edge is a largely revamped and legacy free port of IE. Funny thing is that soon the nonsense about Chromium will be true... maybe that was why they decided to go that route - everyone thought it was a Chromium browser anyway so they just decided "screw it, if you can't beat 'em join 'em". – ChrisM Jun 03 '19 at 16:08
  • @ChrisM Have you been under a rock the last couple months? Stop spreading old information https://www.microsoftedgeinsider.com/en-us/ "Back in December, we announced our intention to adopt the Chromium open source project in the development of Microsoft Edge on the desktop to create better web compatibility for our customers, and less fragmentation of the web for all web developers. Now " – Blanen Jul 03 '19 at 10:33
  • @Blanen ....Thus my comment about Edge becoming a Chromium based browser. But Edge-Chromium is not yet released. The current version of Edge is still based on EdgeHTML which was based on Trident. A fork that MS made in 2015 and continues to maintain to this day. Thus when people imply that checking for Edge is the same as checking for Chrome it's simply untrue. So there's no need to be insulting - you just failed to read my comment properly. – ChrisM Jul 03 '19 at 12:53
  • 1
    Maybe I shouldn't be surprised that people are confused, but to be clear I have encountered this confusion several times before, and long before the announcement about Chromium was made. I assumed that this thread was the same mis-information, but in any case it's simply incorrect. – ChrisM Jul 03 '19 at 12:59
  • 1
    @ChrisM True, sorry. – Blanen Jul 03 '19 at 13:31
  • @Blanen No worries. Happens sometimes :) – ChrisM Jul 03 '19 at 13:33
  • Worked like a charm :) – Hammad Sajid Oct 30 '19 at 07:14
  • This code works in IE ONLY if you place the actual function call in the main js file, not if you export it with webpack in a js module. – Mattia Rasulo Dec 05 '19 at 15:26
  • 1
    @MattiaRasulo thx for commenting. I updated my outdated answer and reduced it to a one-liner. :-) – Mario Dec 06 '19 at 20:14
  • This is the simplest and by far the best solution. Used it to redirect IE users to a page that suggests they rather use Edge. I did not use it for Edge though since I find Edge even better than the clunky Chrome. For some reason Chrome shakes when javascript curtains or carousel photo viewers render but not Edge. – Hmerman6006 May 22 '20 at 18:55
  • Incredible IE: `Object.prototype.hasOwnProperty.call(document, 'documentMode')` returns false, but `document.documentMode === 11` is true, beware – Maxim Mazurok Jun 09 '22 at 09:23
528

Use below JavaScript method :

function msieversion() 
{
    var ua = window.navigator.userAgent;
    var msie = ua.indexOf("MSIE ");

    if (msie > 0) // If Internet Explorer, return version number
    {
        alert(parseInt(ua.substring(msie + 5, ua.indexOf(".", msie))));
    }
    else  // If another browser, return 0
    {
        alert('otherbrowser');
    }

    return false;
}

You may find the details on below Microsoft support site :

How to determine browser version from script

Update : (IE 11 support)

function msieversion() {

    var ua = window.navigator.userAgent;
    var msie = ua.indexOf("MSIE ");

    if (msie > 0 || !!navigator.userAgent.match(/Trident.*rv\:11\./))  // If Internet Explorer, return version number
    {
        alert(parseInt(ua.substring(msie + 5, ua.indexOf(".", msie))));
    }
    else  // If another browser, return 0
    {
        alert('otherbrowser');
    }

    return false;
}
SpiderCode
  • 10,062
  • 2
  • 22
  • 42
165

If all you want to know is if the browser is IE or not, you can do this:

var isIE = false;
var ua = window.navigator.userAgent;
var old_ie = ua.indexOf('MSIE ');
var new_ie = ua.indexOf('Trident/');

if ((old_ie > -1) || (new_ie > -1)) {
    isIE = true;
}

if ( isIE ) {
    //IE specific code goes here
}

Update 1: A better method

I recommend this now. It is still very readable and is far less code :)

var ua = window.navigator.userAgent;
var isIE = /MSIE|Trident/.test(ua);

if ( isIE ) {
  //IE specific code goes here
}

Thanks to JohnnyFun in the comments for the shortened answer :)

Update 2: Testing for IE in CSS

Firstly, if you can, you should use @supports statements instead of JS for checking if a browser supports a certain CSS feature.

.element {
  /* styles for all browsers */
}

@supports (display: grid) {
  .element {
    /* styles for browsers that support display: grid */
  }
}

(Note that IE doesn't support @supports at all and will ignore any styles placed inside an @supports statement.)

If the issue can't be resolved with @supports then you can do this:

// JS

var ua = window.navigator.userAgent;
var isIE = /MSIE|Trident/.test(ua);

if ( isIE ) {
  document.documentElement.classList.add('ie')
}
/* CSS */

.element {
  /* styles that apply everywhere */
}

.ie .element {
  /* styles that only apply in IE */
}

(Note: classList is relatively new to JS and I think, out of the IE browsers, it only works in IE11. Possibly also IE10.)

If you are using SCSS (Sass) in your project, this can be simplified to:

/* SCSS (Sass) */

.element {
  /* styles that apply everywhere */

  .ie & {
    /* styles that only apply in IE */
  }
}

Update 3: Adding Microsoft Edge (not recommended)

If you also want to add Microsoft Edge into the list, you can do the following. However I do not recommend it as Edge is a much more competent browser than IE.

var ua = window.navigator.userAgent;
var isIE = /MSIE|Trident|Edge\//.test(ua);

if ( isIE ) {
  //IE & Edge specific code goes here
}
Daniel Tonon
  • 9,261
  • 5
  • 61
  • 64
  • 6
    Or the same in a few bytes: ms_ie = ~ua.indexOf('MSIE ') || ~ua.indexOf('Trident/'); ;-) – Simon Steinberger Aug 10 '14 at 10:13
  • 12
    My version makes much more immediate sense though to a human but less bytes is always good :) – Daniel Tonon Aug 15 '14 at 00:33
  • 7
    or `ms_ie = !!ua.match(/MSIE|Trident/)` – xori Sep 08 '15 at 16:10
  • 6
    or ms_ie = /MSIE|Trident/.test(ua) – JohnnyFun Oct 14 '16 at 19:22
  • 1
    @SimonSteinberger does the `~` have any significance? – 1.21 gigawatts Feb 20 '17 at 07:19
  • Thanks.. Here's a further simplified one-liner to check: if(/MSIE|Trident/.test(window.navigator.userAgent)) – iPzard Aug 17 '19 at 19:17
  • @iPzard getting rid of the `ua` variable is fine. You don't want to get rid of the `isIE` variable though. Using an `isIE` variable means that you can easily test for IE again multiple times throughout your code without spending extra computation cycles computing the value again. It's also less repetitious. – Daniel Tonon Aug 17 '19 at 19:28
  • I mean, how many times do you need to check if they're on IE? It's not like they can change browsers during the same page view. Imo, if you're checking something that's not changeable during the session (like the user's browser) more than once, the code should probably be refactored to avoid that. Just my opinion. – iPzard Aug 17 '19 at 19:39
  • 1
    One component needs to check for IE. `import isIE from './isIE.js'`. Now another component for whatever reason needs to check for IE, `import isIE from './isIE.js'`. And if that isn't enough to convince you, it is simply better for readability. There are 2 reasons to use a variable: reduce code repetition; and clarify what a piece of code does. When you read `if (/MSIE|Trident/.test(window.navigator.userAgent))` it is far less immediately obvious what it is checking for when compared to `if (isIE)` – Daniel Tonon Aug 17 '19 at 19:49
  • Agree 100% about Edges competency. Edge is as good as dare I say it. Excel. – Hmerman6006 May 22 '20 at 19:07
  • so simple for an IE check. just what i need. thanks! – mars-o Sep 22 '20 at 14:39
48

This returns true for any version of Internet Explorer:

function isIE(userAgent) {
  userAgent = userAgent || navigator.userAgent;
  return userAgent.indexOf("MSIE ") > -1 || userAgent.indexOf("Trident/") > -1 || userAgent.indexOf("Edge/") > -1;
}

The userAgent parameter is optional and it defaults to the browser's user agent.

bendytree
  • 13,095
  • 11
  • 75
  • 91
33

You can use the navigator object to detect user-navigator, you don't need jquery for it, the 4 comments below are already included so this snippet works as expected

if (/MSIE (\d+\.\d+);/.test(navigator.userAgent) || navigator.userAgent.indexOf("Trident/") > -1 ){ 
 // Do stuff with Internet-Exploders ... :)
}

http://www.javascriptkit.com/javatutors/navigator.shtml

john Smith
  • 17,409
  • 11
  • 76
  • 117
31

This is how the Angularjs team is doing it (v 1.6.5):

var msie, // holds major version number for IE, or NaN if UA is not IE.

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

Then there are several lines of code scattered throughout using it as a number such as

if (event === 'input' && msie <= 11) return false;

and

if (enabled && msie < 8) {
ThisClark
  • 14,352
  • 10
  • 69
  • 100
  • window.document.documentMode is undefined in MS Edge – Veselin Vasilev Mar 31 '17 at 04:57
  • 28
    it's undefined in MS Edge because MS Edge is not IE! – JCKödel Feb 14 '18 at 01:04
  • 2
    `document.documentMode` is supported by IE8+. It will be `'undefined'` for Edge or Chrome/FireFox... . I changed this code to `var IEver = window.document.documentMode || (window.attachEvent? 1 : 99);` such that it returns exact IE version for IE8+, 99 for non-IE browsers (usually it will be a modern browser), and 1 for old IE5-7. This is written such because we usually need special work only for some older IE's. So, `if (IEver < 9) { ... }` means if it is an old IE – S.Serpooshan Sep 30 '18 at 11:52
18

You can simply do this:

var isIE = window.document.documentMode ? true : false; // this variable will hold if the current browser is IE

I know the question is old but if someone scrolled that far they can see the simple answer :)

kenan238
  • 398
  • 4
  • 13
10

Method 01:
$.browser was deprecated in jQuery version 1.3 and removed in 1.9

if ( $.browser.msie) {
  alert( "Hello! This is IE." );
}

Method 02:
Using Conditional Comments

<!--[if gte IE 8]>
<p>You're using a recent version of Internet Explorer.</p>
<![endif]-->

<!--[if lt IE 7]>
<p>Hm. You should upgrade your copy of Internet Explorer.</p>
<![endif]-->

<![if !IE]>
<p>You're not using Internet Explorer.</p>
<![endif]>

Method 03:

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

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

Method 04:
Use JavaScript/Manual Detection

/*
     Internet Explorer sniffer code to add class to body tag for IE version.
     Can be removed if your using something like Modernizr.
 */
 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]);

     //append class to body for use with browser support
     if (v > 4)
     {
         $('body').addClass('ie' + v);
     }

 }());

Reference Link

Aamir Shahzad
  • 6,683
  • 8
  • 47
  • 70
  • @radhe I have updated the answer hopefully this will work for you. – Aamir Shahzad Sep 11 '14 at 17:35
  • As a note: **Method 2** will not work in IE10 or better in standard mode. For more information: [Conditional comments are no longer supported](https://msdn.microsoft.com/en-us/library/hh801214(v=vs.85).aspx) – insertusernamehere May 07 '15 at 11:57
  • @insertusernamehere you are very right, for that i think use of `.ie10` class is one of the best options if you are doing some css fix for ie10 only. As internet explorer 10 adds `".ie10"` class to HTML element ``, you can then use it like `.ie10 .myclass {//some css here}` – Aamir Shahzad May 08 '15 at 04:41
10

Using the answers above; simple & condensed returning Boolean:

var isIE = /(MSIE|Trident\/|Edge\/)/i.test(navigator.userAgent);

gdibble
  • 1,341
  • 14
  • 16
9

I just wanted to check if the browser was IE11 or older, because well, they're crap.

function isCrappyIE() {
    var ua = window.navigator.userAgent;
    var crappyIE = false;
    var msie = ua.indexOf('MSIE ');
    if (msie > 0) {// IE 10 or older => return version number        
        crappyIE = true;
    }
    var trident = ua.indexOf('Trident/');
    if (trident > 0) {// IE 11 => return version number        
        crappyIE = true;
    }
    return crappyIE;
}   

if(!isCrappyIE()){console.table('not a crappy browser);}
Bill_VA
  • 913
  • 7
  • 12
8
function detectIE() {
    var ua = window.navigator.userAgent;
    var ie = ua.search(/(MSIE|Trident|Edge)/);

    return ie > -1;
}
headione
  • 106
  • 1
  • 4
6

Using modernizr

Modernizr.addTest('ie', function () {
    var ua = window.navigator.userAgent;
    var msie = ua.indexOf('MSIE ') > 0;
    var ie11 = ua.indexOf('Trident/') > 0;
    var ie12 = ua.indexOf('Edge/') > 0;
    return msie || ie11 || ie12;
});
kevnk
  • 18,733
  • 3
  • 28
  • 30
  • Doesn't answer the question as Edge is not IE. Also Edge is not IE12. When Chromium-based Edge is released, you should also add Chrome or Opera to this list. (Whatever you want to achieve by this, it would be easier to detect Firefox then) – hda Dec 16 '18 at 17:22
6

Or this really short version, returns true if the browsers is Internet Explorer:

function isIe() {
    return window.navigator.userAgent.indexOf("MSIE ") > 0
        || !!navigator.userAgent.match(/Trident.*rv\:11\./);
}
Floris
  • 2,727
  • 2
  • 27
  • 47
5

Try this if you are using jquery version >=1.9,

var browser;
jQuery.uaMatch = function (ua) {
    ua = ua.toLowerCase();

    var match = /(chrome)[ \/]([\w.]+)/.exec(ua) ||
        /(webkit)[ \/]([\w.]+)/.exec(ua) ||
        /(opera)(?:.*version|)[ \/]([\w.]+)/.exec(ua) ||
        /(msie) ([\w.]+)/.exec(ua) || 
        ua.indexOf("compatible") < 0 && /(mozilla)(?:.*? rv:([\w.]+)|)/.exec(ua) ||
       /(Trident)[\/]([\w.]+)/.exec(ua) || [];

    return {
        browser: match[1] || "",
        version: match[2] || "0"
    };
};
// Don't clobber any existing jQuery.browser in case it's different
if (!jQuery.browser) {
    matched = jQuery.uaMatch(navigator.userAgent);
    browser = {};

    if (matched.browser) {
        browser[matched.browser] = true;
        browser.version = matched.version;
    }

    // Chrome is Webkit, but Webkit is also Safari.
    if (browser.chrome) {
        browser.webkit = true;
    } else if (browser.webkit) {
        browser.safari = true;
    }

    jQuery.browser = browser;
}

If using jQuery version <1.9 ($.browser was removed in jQuery 1.9) use the following code instead:

$('.myClass').on('click', function (event) {
    if ($.browser.msie) {
        alert($.browser.version);
    }
});
Rohan Kumar
  • 40,431
  • 11
  • 76
  • 106
5

Yet another simple (yet human readable) function to detect if the browser is IE or not (ignoring Edge, which isn't bad at all):

function isIE() {
  var ua = window.navigator.userAgent;
  var msie = ua.indexOf('MSIE '); // IE 10 or older
  var trident = ua.indexOf('Trident/'); //IE 11

  return (msie > 0 || trident > 0);
}
Chuck Le Butt
  • 47,570
  • 62
  • 203
  • 289
4

If you don't want to use the useragent, you could also just do this for checking if the browser is IE. The commented code actually runs in IE browsers and turns the "false" to "true".

var isIE = /*@cc_on!@*/false;
if(isIE){
    //The browser is IE.
}else{
    //The browser is NOT IE.
}   
dev4life
  • 880
  • 2
  • 8
  • 18
3

I know this is an old question, but in case anyone comes across it again and has issues with detecting IE11, here is a working solution for all current versions of IE.

var isIE = false;
if (navigator.userAgent.indexOf('MSIE') !== -1 || navigator.appVersion.indexOf('Trident/') > 0) {
    isIE = true;   
}
Ty Bailey
  • 2,392
  • 11
  • 46
  • 79
3

i've used this

function notIE(){
    var ua = window.navigator.userAgent;
    if (ua.indexOf('Edge/') > 0 || 
        ua.indexOf('Trident/') > 0 || 
        ua.indexOf('MSIE ') > 0){
       return false;
    }else{
        return true;                
    }
}
andryou
  • 3
  • 3
Jop Knoppers
  • 676
  • 1
  • 10
  • 22
3

Necromancing.

In order to not depend on the user-agent string, just check for a few properties:

if (document.documentMode) 
{
    console.log('Hello Microsoft IE User!');
}

if (!document.documentMode && window.msWriteProfilerMark) {
    console.log('Hello Microsoft Edge User!');
}

if (document.documentMode || window.msWriteProfilerMark) 
{
    console.log('Hello Microsoft User!');
}

if (window.msWriteProfilerMark) 
{
    console.log('Hello Microsoft User in fewer characters!');
}

Also, this detects the new Chredge/Edgium (Anaheim):

function isEdg()
{ 

    for (var i = 0, u="Microsoft", l =u.length; i < navigator.plugins.length; i++)
    {
        if (navigator.plugins[i].name != null && navigator.plugins[i].name.substr(0, l) === u)
            return true;
    }

    return false;
}

And this detects chromium:

function isChromium()
{ 

    for (var i = 0, u="Chromium", l =u.length; i < navigator.plugins.length; i++)
    {
        if (navigator.plugins[i].name != null && navigator.plugins[i].name.substr(0, l) === u)
            return true;
    }

    return false;
}

And this Safari:

if(window.safari)
{
    console.log("Safari, yeah!");
}
Stefan Steiger
  • 78,642
  • 66
  • 377
  • 442
2

@SpiderCode's solution does not work with IE 11. Here is the best solution that I used henceforth in my code where I need browser detection for particular feature.

IE11 no longer reports as MSIE, according to this list of changes, it's intentional to avoid mis-detection.

What you can do if you really want to know it's IE is to detect the Trident/ string in the user agent if navigator.appName returns Netscape, something like (the untested);

Thanks to this answer

function isIE()
{
  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 == -1 ? false: true;
}
Community
  • 1
  • 1
Anuj Kulkarni
  • 2,261
  • 5
  • 32
  • 42
2

Many answers here, and I'd like to add my input. IE 11 was being such an ass concerning flexbox (see all its issues and inconsistencies here) that I really needed an easy way to check if a user is using any IE browser (up to and including 11) but excluding Edge, because Edge is actually pretty nice.

Based on the answers given here, I wrote a simple function returning a global boolean variable which you can then use down the line. It's very easy to check for IE.

var isIE;
(function() {
    var ua = window.navigator.userAgent,
        msie = ua.indexOf('MSIE '),
        trident = ua.indexOf('Trident/');

    isIE = (msie > -1 || trident > -1) ? true : false;
})();

if (isIE) {
    alert("I am an Internet Explorer!");
}

This way you only have to do the look up once, and you store the result in a variable, rather than having to fetch the result on each function call. (As far as I know you don't even have to wait for document ready to execute this code as the user-agent is not related to the DOM.)

Bram Vanroy
  • 27,032
  • 24
  • 137
  • 239
1

Below I found elegant way of doing this while googling ---

/ detect IE
var IEversion = detectIE();

if (IEversion !== false) {
  document.getElementById('result').innerHTML = 'IE ' + IEversion;
} else {
  document.getElementById('result').innerHTML = 'NOT IE';
}

// add details to debug result
document.getElementById('details').innerHTML = window.navigator.userAgent;

/**
 * detect IE
 * returns version of IE or false, if browser is not Internet Explorer
 */
function detectIE() {
  var ua = window.navigator.userAgent;

  // Test values; Uncomment to check result …

  // 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';

  // IE 12 / Spartan
  // 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 (IE 12+)
  // 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 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;
}
Rameshwar Vyevhare
  • 2,699
  • 2
  • 28
  • 34
  • 1
    This is exactly the code from [my pen at CodePen](http://codepen.io/gapcode/pen/vEJNZN), that is part of [my answer to this question](http://stackoverflow.com/questions/19999388/check-if-user-is-using-ie-with-jquery#answer-21712356). ;-) – Mario Feb 09 '16 at 14:32
  • 1
    Yes I used the same but stack-overflow people don't wants to share link. will update link in reference here onwards. Thanks for the great work Mario. – Rameshwar Vyevhare Feb 10 '16 at 05:00
1

Update to SpiderCode's answer to fix issues where the string 'MSIE' returns -1 but it matches 'Trident'. It used to return NAN, but now returns 11 for that version of IE.

   function msieversion() {
       var ua = window.navigator.userAgent;
       var msie = ua.indexOf("MSIE ");
       if (msie > -1) {
           return ua.substring(msie + 5, ua.indexOf(".", msie));
       } else if (navigator.userAgent.match(/Trident.*rv\:11\./)) {
           return 11;
       } else {
           return false;
       }
    }
JeremyS
  • 427
  • 2
  • 7
1

I landed on this page in 2020, and I see that till IE5 all userAgent string have Trident, I'm not sure if they have changed anything. So checking only for Trident in the userAgent worked for me.

var isIE = navigator.userAgent.indexOf('Trident') > -1;
Anand Bhushan
  • 765
  • 8
  • 18
1

This is another way to detect IE without trying to look at the User-Agent:

var usingIE="__IE_DEVTOOLBAR_CONSOLE_EVAL_ERROR" in document;
alert("You are"+(usingIE?"":"n't")+" using Internet Explorer.");

I happened to find this by accident when I was testing if my site worked on IE, and I went to the debugger and clicked the folder icon. It has my scripts, and also a Dynamic Scripts folder that I didn't have. I opened it and found lots of browsertools.library.js files. Inside them I found stuff like:

document.__IE_DEVTOOLBAR_CONSOLE_EVAL_RESULT = undefined;
document.__IE_DEVTOOLBAR_CONSOLE_EVAL_ERROR = false;
document.__IE_DEVTOOLBAR_CONSOLE_EVAL_ERRORCODE = undefined;
try{
document.__IE_DEVTOOLBAR_CONSOLE_EVAL_RESULT = eval("\r\n//# sourceURL=browsertools://browsertools.library.js");
}
catch( eObj ){
document.__IE_DEVTOOLBAR_CONSOLE_EVAL_ERRORCODE = eObj.number;
document.__IE_DEVTOOLBAR_CONSOLE_EVAL_RESULT = eObj.message || eObj.description || eObj.toString();
document.__IE_DEVTOOLBAR_CONSOLE_EVAL_ERROR = true;
}

So I used these to test if the user's browser was IE. Just note this only works if you want to know if they have IE, not exactly what version of IE they have.

Lakshya Raj
  • 1,669
  • 3
  • 10
  • 34
0

You can dectect all Internet Explorer (Last Version Tested 12).

<script>
    var $userAgent = '';
    if(/MSIE/i['test'](navigator['userAgent'])==true||/rv/i['test'](navigator['userAgent'])==true||/Edge/i['test'](navigator['userAgent'])==true){
       $userAgent='ie';
    } else {
       $userAgent='other';
    }

    alert($userAgent);
</script>

See here https://jsfiddle.net/v7npeLwe/

Rogerio de Moraes
  • 1,527
  • 18
  • 15
0
function msieversion() {
var ua = window.navigator.userAgent;
console.log(ua);
var msie = ua.indexOf("MSIE ");

if (msie > -1 || navigator.userAgent.match(/Trident.*rv:11\./)) { 
    // If Internet Explorer, return version numbe
    // You can do what you want only in IE in here.
    var version_number=parseInt(ua.substring(msie + 5, ua.indexOf(".", msie)));
    if (isNaN(version_number)) {
        var rv_index=ua.indexOf("rv:");
        version_number=parseInt(ua.substring(rv_index+3,ua.indexOf(".",rv_index)));
    }
    console.log(version_number);
} else {       
    //other browser   
    console.log('otherbrowser');
}
}

You should see the result in console, please use chrome Inspect.

Lee Li
  • 392
  • 2
  • 5
  • 11
0

I've placed this code in the document ready function and it only triggers in internet explorer. Tested in Internet Explorer 11.

var ua = window.navigator.userAgent;
ms_ie = /MSIE|Trident/.test(ua);
if ( ms_ie ) {
    //Do internet explorer exclusive behaviour here
}
0

This only work below IE 11 version.

var ie_version = parseInt(window.navigator.userAgent.substring(window.navigator.userAgent.indexOf("MSIE ") + 5, window.navigator.userAgent.indexOf(".", window.navigator.userAgent.indexOf("MSIE "))));

console.log("version number",ie_version);

Murali Krishna
  • 96
  • 1
  • 12
0

JavaScript function to detect the version of Internet Explorer or Edge

function ieVersion(uaString) {
  uaString = uaString || navigator.userAgent;
  var match = /\b(MSIE |Trident.*?rv:|Edge\/)(\d+)/.exec(uaString);
  if (match) return parseInt(match[2])
}
Shohel
  • 3,886
  • 4
  • 38
  • 75
-1

Try doing like this

if ($.browser.msie && $.browser.version == 8) {
    //my stuff

}
Deepak Kumar
  • 221
  • 3
  • 17
-1

I think it will help you Here

function checkIsIE() {
    var isIE = false;
    if (navigator.userAgent.indexOf('MSIE') !== -1 || navigator.appVersion.indexOf('Trident/') > 0) {
        isIE = true;
    }
    if (isIE)  // If Internet Explorer, return version number
    {
        kendo.ui.Window.fn._keydown = function (originalFn) {
            var KEY_ESC = 27;
            return function (e) {
                if (e.which !== KEY_ESC) {
                    originalFn.call(this, e);
                }
            };
        }(kendo.ui.Window.fn._keydown);

        var windowBrowser = $("#windowBrowser").kendoWindow({
            modal: true,
            id: 'dialogBrowser',
            visible: false,
            width: "40%",
            title: "Thông báo",
            scrollable: false,
            resizable: false,
            deactivate: false,
            position: {
                top: 100,
                left: '30%'
            }
        }).data('kendoWindow');
        var html = '<br /><div style="width:100%;text-align:center"><p style="color:red;font-weight:bold">Please use the browser below to use the tool</p>';
        html += '<img src="/Scripts/IPTVClearFeePackage_Box/Images/firefox.png"/>';
        html += ' <img src="/Scripts/IPTVClearFeePackage_Box/Images/chrome.png" />';
        html += ' <img src="/Scripts/IPTVClearFeePackage_Box/Images/opera.png" />';
        html += '<hr /><form><input type="button" class="btn btn-danger" value="Đóng trình duyệt" onclick="window.close()"></form><div>';
        windowBrowser.content(html);
        windowBrowser.open();

        $("#windowBrowser").parent().find(".k-window-titlebar").remove();
    }
    else  // If another browser, return 0
    {
        return false;
    }
}
AirBlack
  • 135
  • 1
  • 9
-3

You can use $.browser to get name, vendor and version information.

See http://api.jquery.com/jQuery.browser/

Roemer
  • 3,566
  • 1
  • 16
  • 32
  • 7
    "This property was removed in jQuery 1.9 and is available only through the jQuery.migrate plugin." – Reeno Nov 15 '13 at 10:57