¿Cómo puedo detectar Internet Explorer (IE) y Microsoft Edge usando JavaScript?


He mirado a mi alrededor mucho, y entiendo que hay un montón de maneras de detectar Internet Explorer.

Mi problema es este: Tengo un área en mi documento HTML, que cuando se hace clic, llama a una función JavaScript que es incompatible con Internet explorer de cualquier tipo. Quiero detectar si se está utilizando IE, y si es así, establecer la variable a true.

El problema es que estoy escribiendo mi código desde Notepad++, y cuando corro el código HTML en el navegador, ninguno de los métodos para detectar IE trabajo. Creo que el problema es que me estoy quedando sin Notepad++. Necesito ser capaz de detectar IE, de modo que basado en la variable, puedo desactivar esa área del sitio. He intentado esto:

var isIE10 = false;

if (navigator.userAgent.indexOf("MSIE 10") > -1) {
    // this is internet explorer 10
    isIE10 = true;
   window.alert(isIE10);
}

var isIE = (navigator.userAgent.indexOf("MSIE") != -1);

if(isIE){
    if(!isIE10){
    window.location = 'pages/core/ie.htm';
    }
}

Pero no funciona. ¿Cómo puedo detectar IE desde Notepad++? Eso es de lo que estoy probando el HTML, pero necesito un método que funcione con eso.

Editar

He notado que alguien ha marcado esto como un duplicado, y eso es comprensible. Supongo que no fui claro. No puedo usar un Respuesta jQuery, por lo que esto no es un duplicado, ya que estoy pidiendo una respuesta JS vainilla.

Editar #2

¿Hay también una manera de detectar el navegador Microsoft Edge?

Author: Bharata, 2015-08-01

11 answers

No se por qué, pero no estoy viendo "Edge" en el UserAgent como todo el mundo está hablando, así que tuve que tomar otra ruta que puede ayudar a algunas personas.

En lugar de mirar al navegador.UserAgent, miré navigator.appName para distinguir si era IE

Después de determinar que el navegador es IE11 o Edge, entonces miré a navegador.appVersion. Noté que en IE11 la cadena era bastante larga con mucha información dentro de ella. Escogí arbitrariamente la palabra "Tridente", que definitivamente no está en el navegador.appVersion para Edge. Probar esta palabra me permitió distinguir las dos.

A continuación se muestra una función que devolverá un valor numérico del Internet Explorer en el que se encuentra el usuario. Si en Microsoft Edge devuelve el número 12.

Buena suerte y espero que esto ayude!

function Check_Version(){
    var rv = -1; // Return value assumes failure.

    if (navigator.appName == 'Microsoft Internet Explorer'){

       var ua = navigator.userAgent,
           re  = new RegExp("MSIE ([0-9]{1,}[\\.0-9]{0,})");

       if (re.exec(ua) !== null){
         rv = parseFloat( RegExp.$1 );
       }
    }
    else if(navigator.appName == "Netscape"){                       
       /// in IE 11 the navigator.appVersion says 'trident'
       /// in Edge the navigator.appVersion does not say trident
       if(navigator.appVersion.indexOf('Trident') === -1) rv = 12;
       else rv = 11;
    }       

    return rv;          
}
 23
Author: skribbz14,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-08-20 00:45:14

Aquí está la última forma correcta que sé de cómo comprobar IE y Edge:

if (/MSIE 10/i.test(navigator.userAgent)) {
   // This is internet explorer 10
   window.alert('isIE10');
}

if (/MSIE 9/i.test(navigator.userAgent) || /rv:11.0/i.test(navigator.userAgent)) {
    // This is internet explorer 9 or 11
    window.location = 'pages/core/ie.htm';
}

if (/Edge\/\d./i.test(navigator.userAgent)){
   // This is Microsoft Edge
   window.alert('Microsoft Edge');
}

Tenga en cuenta que no necesita la var extrae10 adicional en su código porque ahora realiza comprobaciones muy específicas.

También echa un vistazo a esta página para las últimas cadenas de agentes de usuario IE y Edge porque esta respuesta puede quedar obsoleta en algún momento: https://msdn.microsoft.com/en-us/library/hh869301%28v=vs.85%29.aspx

 72
Author: Reinout van Kempen,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-05-25 15:35:54

Estoy usando UAParser https://github.com/faisalman/ua-parser-js

var a = new UAParser();
var name = a.getResult().browser.name;
var version = a.getResult().browser.version;
 11
Author: Oren Gal,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-09-23 15:20:35

El tema es un poco viejo, pero ya que los scripts aquí detectan Firefox como un Falso Positivo (EDGE v12), aquí está la versión que uso:

function isIEorEDGE(){
  if (navigator.appName == 'Microsoft Internet Explorer'){
    return true; // IE
  }
  else if(navigator.appName == "Netscape"){                       
     return navigator.appVersion.indexOf('Edge') > -1; // EDGE
  }       

  return false;
}

Que por supuesto se puede escribir de una manera más concisa:

function isIEorEDGE(){
  return navigator.appName == 'Microsoft Internet Explorer' || (navigator.appName == "Netscape" && navigator.appVersion.indexOf('Edge') > -1);
}
 11
Author: GavinoGrifoni,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-07-29 08:16:03
// detect IE8 and above, and Edge
if (document.documentMode || /Edge/.test(navigator.userAgent)) {
    ... do something
}

Explicación:

document.documentMode

Una propiedad de solo IE, disponible por primera vez en IE8.

/Edge/

Una expresión regular para buscar la cadena 'Edge' - que luego probamos con el 'navigator.Propiedad del agente de usuario

 7
Author: Chris Halcrow,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-10-18 21:52:57

Si solo desea dar a los usuarios que utilizan un navegador MS una advertencia o algo, este código debería ser bueno.

HTML:

<p id="IE">You are not using a microsoft browser</p>

Javascript:

using_ms_browser = navigator.appName == 'Microsoft Internet Explorer' || (navigator.appName == "Netscape" && navigator.appVersion.indexOf('Edge') > -1) || (navigator.appName == "Netscape" && navigator.appVersion.indexOf('Trident') > -1);

if (using_ms_browser == true){
    document.getElementById('IE').innerHTML = "You are using a MS browser"
}

Gracias a @ GavinoGrifoni

 4
Author: patchie,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-09-13 09:53:28

Esta función funcionó perfectamente para mí. También detecta Edge.

Originalmente de este Codepen:

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

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

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

Entonces puedes usar if (detectIE()) { /* do IE stuff */ } en tu código.

 4
Author: phocks,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-10-18 06:47:36

Use este recorte: var IE = (navigator.userAgent.indexOf("Edge") > -1 || navigator.userAgent.indexOf("Trident/7.0") > -1) ? true : false;

 2
Author: AminAmiriDarban,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-03-07 15:01:39

Para mí mejor esto:

var uA = window.navigator.userAgent,
    onlyIEorEdge = /msie\s|trident\/|edge\//i.test(uA) && !!( document.uniqueID || window.MSInputMethodContext),
    checkVersion = (onlyIEorEdge && +(/(edge\/|rv:|msie\s)([\d.]+)/i.exec(uA)[2])) || NaN;

Go run: http://output.jsbin.com/solicul/1/ o http://jsfiddle.net/Webnewbie/apa1nvu8/

 2
Author: James Peter,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-07-12 21:24:12

Aquí hay una clase de javascript que detecta IE10, IE11 y Edge.
El objeto Navigator se inyecta con fines de prueba.

var DeviceHelper = function (_navigator) {
    this.navigator = _navigator || navigator;
};
DeviceHelper.prototype.isIE = function() {
    if(!this.navigator.userAgent) {
        return false;
    }

    var IE10 = Boolean(this.navigator.userAgent.match(/(MSIE)/i)),
        IE11 = Boolean(this.navigator.userAgent.match(/(Trident)/i));
    return IE10 || IE11;
};

DeviceHelper.prototype.isEdge = function() {
    return !!this.navigator.userAgent && this.navigator.userAgent.indexOf("Edge") > -1;
};

DeviceHelper.prototype.isMicrosoftBrowser = function() {
    return this.isEdge() || this.isIE();
};
 0
Author: Tomas Prado,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-04-27 13:42:20

En primer lugar no es el problema Notepad++ seguro. Es su "String Matching problem "

La cadena común en todas las versiones de IE es MSIE Echa un vistazo a las diversas cadenas UserAgent en http://www.useragentstring.com/pages/Internet%20Explorer /

if(navigator.userAgent.indexOf("MSIE") != -1){
   alert('I am Internet Explorer!!');
}
 -4
Author: Amit Prabhu Parrikar,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-08-01 11:47:48