Jak wykryć IE11?

Gdy chcę wykryć IE używam tego kodu:

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 );
  }
  return rv;
}
function checkVersion()
{
  var msg = "You're not using Internet Explorer.";
  var ver = getInternetExplorerVersion();

  if ( ver > -1 )
  {
    msg = "You are using IE " + ver;
  }
  alert( msg );
}

Ale IE11 zwraca "nie używasz Internet Explorera". Jak mogę to wykryć?

Author: Paul Sweatte, 2013-07-28

15 answers

IE11 nie zgłasza już jako MSIE, zgodnie z Ta lista zmian {[7] }jest zamierzona, aby uniknąć błędnego wykrycia.

Co możesz zrobić, jeśli naprawdę chcesz wiedzieć, że to IE jest wykrywanie Trident/ string W user agencie, jeśli navigator.appName zwraca Netscape, coś w rodzaju (the untested);

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

console.log('IE version:', getInternetExplorerVersion());

Zauważ, że IE11 (afaik)nadal jest w podglądzie, a agent użytkownika może się zmienić przed wydaniem.

 205
Author: Joachim Isaksson,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-05-03 13:21:05

Użyj !(window.ActiveXObject) && "ActiveXObject" in window do jawnego wykrycia IE11.

Aby wykryć dowolną wersję IE (pre-Edge, "Trident"), użyj "ActiveXObject" in window.

 79
Author: mcw0933,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-04-11 15:28:59

Użyj MSInputMethodContext jako części kontroli wykrywania funkcji. Na przykład:

//Appends true for IE11, false otherwise
window.location.hash = !!window.MSInputMethodContext && !!document.documentMode;

Referencje

 33
Author: Paul Sweatte,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-06-27 14:04:14

Przeczytałem Twoje odpowiedzi i zrobiłem miks. Wydaje się, że działa z Windows XP (IE7/IE8) i Windows 7 (IE9 / IE10 / IE11).

function ie_ver(){  
    var iev=0;
    var ieold = (/MSIE (\d+\.\d+);/.test(navigator.userAgent));
    var trident = !!navigator.userAgent.match(/Trident\/7.0/);
    var rv=navigator.userAgent.indexOf("rv:11.0");

    if (ieold) iev=new Number(RegExp.$1);
    if (navigator.appVersion.indexOf("MSIE 10") != -1) iev=10;
    if (trident&&rv!=-1) iev=11;

    return iev;         
}

Oczywiście jeśli zwrócę 0, oznacza brak IE.

 15
Author: Fabio,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-12-29 12:48:42

Pobierz wersję IE z User-agenta

var ie = 0;
try { ie = navigator.userAgent.match( /(MSIE |Trident.*rv[ :])([0-9]+)/ )[ 2 ]; }
catch(e){}

Jak to działa: ciąg User-agent dla wszystkich wersji IE zawiera część " MSIE space version" or " Trident other-text rv space-or-colon wersja ". Wiedząc o tym, pobieramy numer wersji z String.match() wyrażenia regularnego. Blok try-catch jest używany do skrócenia kodu, w przeciwnym razie musielibyśmy przetestować granice tablic dla innych niż IE przeglądarki.

Uwaga: user-agent może zostać sfałszowany lub pominięty, czasami nieumyślnie, jeśli użytkownik ustawił przeglądarkę na "tryb zgodności". Choć w praktyce nie wydaje się to zbyt dużym problemem.


Pobierz wersję IE bez User-agenta

var d = document, w = window;
var ie = ( !!w.MSInputMethodContext ? 11 : !d.all ? 99 : w.atob ? 10 : 
d.addEventListener ? 9 : d.querySelector ? 8 : w.XMLHttpRequest ? 7 : 
d.compatMode ? 6 : w.attachEvent ? 5 : 1 );

Jak to działa: każda wersja IE dodaje wsparcie dla dodatkowych funkcji nie znalezionych w poprzednich wersjach. Możemy więc testować funkcje odgórnie. A ternary sequence jest tutaj używane dla zwięzłości, chociaż if-then i switch mogą działać równie dobrze. Zmienna ie jest ustawiona na liczbę całkowitą 5-11, lub 1 dla starszych lub 99 dla nowszych / nie-IE. Możesz ustawić go na 0, jeśli chcesz dokładnie przetestować IE 1-11.

Uwaga: wykrywanie obiektów może się zepsuć, jeśli kod jest uruchamiany na stronie ze skryptami innych firm, które dodają polyfills dla rzeczy takich jak document.addEventListener. W takich sytuacjach user-agent jest najlepszym opcja.


Wykryj, czy przeglądarka jest nowoczesna

Jeśli interesuje Cię tylko to, czy przeglądarka obsługuje większość standardów HTML 5 i CSS 3, możesz rozsądnie założyć, że IE 8 i niższe pozostają głównym problemem aplikacji. Testowanie dla window.getComputedStyle da ci dość dobrą mieszankę nowoczesnych przeglądarek (IE 9, FF 4, Chrome 11, Safari 5, Opera 11.5). IE 9 znacznie poprawia obsługę standardów, ale natywna animacja CSS wymaga IE 10.

var isModernBrowser = ( !document.all || ( document.all && document.addEventListener ) ); 
 11
Author: Beejor,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-08-27 18:37:17

Angular JS robi tak.

msie = parseInt((/msie (\d+)/.exec(navigator.userAgent.toLowerCase()) || [])[1]);
if (isNaN(msie)) {
  msie = parseInt((/trident\/.*; rv:(\d+)/.exec(navigator.userAgent.toLowerCase()) || [])[1]);
}

Msie będzie liczbą dodatnią, jeśli jego IE i NaN dla innych przeglądarek, takich jak chrome, firefox.

Dlaczego ?

Od wersji Internet Explorer 11 ciąg User-agent uległ znaczącej zmianie.

Zobacz to:

Msdn #1 msdn #2

 8
Author: Vishal Sharma,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-08-25 18:10:58

Rozwiązanie:

function GetIEVersion() {
  var sAgent = window.navigator.userAgent;
  var Idx = sAgent.indexOf("MSIE");
  // If IE, return version number.
  if (Idx > 0)
    return parseInt(sAgent.substring(Idx+ 5, sAgent.indexOf(".", Idx)));

  // If IE 11 then look for Updated user agent string.
  else if (!!navigator.userAgent.match(/Trident\/7\./))
    return 11;

  else
    return 0; //It is not IE

}
if ((GetIEVersion() > 0) || (navigator.userAgent.toLowerCase().indexOf('firefox') > -1)){
  alert("This is IE " + GetIEVersion());
}else {
  alert("This no is IE ");
}		
 7
Author: coperniko,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-09-11 05:59:04

Używam prostszej metody:

Obiekt navigator global posiada właściwość touchpoints, w Internet Exlorer 11 nazywa się msMaxTouchPoints tho.

Więc jeśli szukasz:

navigator.msMaxTouchPoints !== void 0 

Znajdziesz Internet Explorer 11.

 3
Author: Dvid Silva,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-06-23 01:39:59
var ua = navigator.userAgent.toString().toLowerCase();
var match = /(trident)(?:.*rv:([\w.]+))?/.exec(ua) ||/(msie) ([\w.]+)/.exec(ua)||['',null,-1];
var rv = match[2];
return rv;
 2
Author: areschen,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-08-12 01:18:23

Spróbuj Tego:

var trident = !!navigator.userAgent.match(/Trident\/7.0/);
var net = !!navigator.userAgent.match(/.NET4.0E/);
var IE11 = trident && net
var IEold = ( navigator.userAgent.match(/MSIE/i) ? true : false );
if(IE11 || IEold){
alert("IE")
}else{
alert("Other")
}
 2
Author: Krunal,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-10-24 10:55:48

To wydaje się być lepszą metodą. "indexOf" zwraca -1 jeśli nic nie jest dopasowane. Nie nadpisuje istniejących klas na ciele, tylko dodaje je.

// add a class on the body ie IE 10/11
var uA = navigator.userAgent;
if(uA.indexOf('Trident') != -1 && uA.indexOf('rv:11') != -1){
    document.body.className = document.body.className+' ie11';
}
if(uA.indexOf('Trident') != -1 && uA.indexOf('MSIE 10.0') != -1){
    document.body.className = document.body.className+' ie10';
}
 1
Author: joe,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-07-16 09:45:55

Wykryj większość przeglądarek za pomocą tego:

var getBrowser = function(){
  var navigatorObj = navigator.appName,
      userAgentObj = navigator.userAgent,
      matchVersion;
  var match = userAgentObj.match(/(opera|chrome|safari|firefox|msie|trident)\/?\s*(\.?\d+(\.\d+)*)/i);
  if( match && (matchVersion = userAgentObj.match(/version\/([\.\d]+)/i)) !== null) match[2] = matchVersion[1];
  //mobile
  if (navigator.userAgent.match(/iPhone|Android|webOS|iPad/i)) {
    return match ? [match[1], match[2], mobile] : [navigatorObj, navigator.appVersion, mobile];
  }
  // web browser
  return match ? [match[1], match[2]] : [navigatorObj, navigator.appVersion, '-?'];
};

Https://gist.github.com/earlonrails/5266945

 0
Author: earlonrails,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-10-02 20:44:31

Użyłem zdarzenia onscroll w elemencie z paskiem przewijania. Po uruchomieniu w IE dodałem następującą walidację:

onscroll="if (document.activeElement==this) ignoreHideOptions()"
 0
Author: Martin,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-04-08 13:59:09

Tylko dla przeglądarki IE:

var ie = 'NotIE'; //IE5-11, Edge+
    if( !!document.compatMode ) {
        if( !("ActiveXObject" in window) ) ) ie = 'EDGE';
        if( !!document.uniqueID){
            if('ActiveXObject' in window && !window.createPopup ){ ie = 11; }
            else if(!!document.all){
                    if(!!window.atob){ie = 10;}
                    else if(!!document.addEventListener) {ie = 9;}
                    else if(!!document.querySelector){ie = 8;}
                    else if(!!window.XMLHttpRequest){ie = 7;}
                    else if(!!document.compatMode){ie = 6;}
                    else ie = 5;
                }
        }
    }

Use alert (ie);

Testowanie:

var browserVersionExplorer = (function() {
    var ie = '<s>NotIE</s>',
        me = '<s>NotIE</s>';

    if (/msie\s|trident\/|edge\//i.test(window.navigator.userAgent) && !!(document.documentMode || document.uniqueID || window.ActiveXObject || window.MSInputMethodContext)) {
            if (!!window.MSInputMethodContext) {
                ie = !("ActiveXObject" in window) ? 'EDGE' : 11;
            } else if (!!document.uniqueID) {
                if (!!(window.ActiveXObject && document.all)) {
                    if (document.compatMode == "CSS1Compat" && !!window.DOMParser ) {
                        ie = !!window.XMLHttpRequest ? 7 : 6;
                    } else {
                        ie = !!(window.createPopup && document.getElementById) ? parseFloat('5.5') : 5;
                    }
                    if (!!document.documentMode && !!document.querySelector ) {
                        ie = !!(window.atob && window.matchMedia) ? 10 : ( !!document.addEventListener ? 9 : 8);
                    }
                } else ie = !!document.all ? 4 : (!!window.navigator ? 3 : 2);
            }
        }
        
    return ie > 1 ? 'IE ' + ie : ie;
})();

 alert(browserVersionExplorer);

Aktualizacja 01 CZE 2017

Teraz przydałoby się coś prostszego i prostszego:

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;
 0
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/doraprojects.net/template/agent.layouts/content.php on line 54
2017-06-01 14:15:46

Szczerze mówiąc powiedziałbym, że użyj biblioteki, która robi to, czego potrzebujesz (jak Platforma.js na przykład). W pewnym momencie wszystko się zmieni i biblioteka będzie przystosowana do tych zmian, a ręczne parsowanie przy użyciu wyrażeń regularnych nie powiedzie się.

Dzięki Bogu IE odchodzi...

 0
Author: Matthias Hryniszak,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-01-14 22:06:49