[javascript] Check if user is using IE

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

The answer is


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


Try doing like this

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

}

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\./);
}

Using the answers above; simple & condensed returning Boolean:

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


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) {

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

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
}

function detectIE() {
    var ua = window.navigator.userAgent;
    var ie = ua.search(/(MSIE|Trident|Edge)/);

    return ie > -1;
}

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/


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.


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

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


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

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

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

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

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

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


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

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;

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.


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

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

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


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

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
}

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.)


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

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

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


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

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to internet-explorer

Support for ES6 in Internet Explorer 11 The response content cannot be parsed because the Internet Explorer engine is not available, or Flexbox not working in Internet Explorer 11 IE and Edge fix for object-fit: cover; "Object doesn't support property or method 'find'" in IE How to make promises work in IE11 Angular 2 / 4 / 5 not working in IE11 Text in a flex container doesn't wrap in IE11 How can I detect Internet Explorer (IE) and Microsoft Edge using JavaScript? includes() not working in all browsers

Examples related to browser-detection

Detecting iOS / Android Operating system Check if user is using IE How to detect IE11? Detecting a mobile browser Detect IE version (prior to v9) in JavaScript How to detect Safari, Chrome, IE, Firefox and Opera browser? Detect Safari browser How can you detect the version of a browser? Detect Safari using jQuery Best way to check for IE less than 9 in JavaScript without library