Wykrywanie wersji IE (przed v9) w JavaScript

Chcę przerzucić użytkowników naszej strony na stronę błędu, jeśli używają wersji Internet Explorer przed v9. To po prostu nie jest warte naszego czasu i pieniędzy, aby wspierać IE pre-v9. Użytkownicy wszystkich innych przeglądarek innych niż IE są w porządku i nie powinni być odbijani. Oto proponowany kod:

if(navigator.appName.indexOf("Internet Explorer")!=-1){     //yeah, he's using IE
    var badBrowser=(
        navigator.appVersion.indexOf("MSIE 9")==-1 &&   //v9 is ok
        navigator.appVersion.indexOf("MSIE 1")==-1  //v10, 11, 12, etc. is fine too
    );

    if(badBrowser){
        // navigate to error page
    }
}
Czy ten kod wystarczy?

Do głowy kilka komentarzy, które prawdopodobnie będą po mojej stronie:

  1. tak, Wiem, że użytkownicy mogą podrobić swój useragent ciąg znaków. Nie martwię się.
  2. Tak, Ja wiedz, że programiści wolą sniffing out obsługi funkcji zamiast typu przeglądarki, ale nie czuję, że to podejście ma sens w tym przypadku. Wiem już, że wszystkie (istotne) przeglądarki spoza IE obsługują funkcje, których potrzebuję, a wszystkie pre-v9 IE przeglądarki Nie. sprawdzanie funkcji po funkcji w całej witrynie byłoby marnotrawstwem.
  3. tak, Wiem, że ktoś próbujący uzyskać dostęp do strony za pomocą IE v1 (lub >= 20) Nie ustawiłby' badBrowser ' na true i strona z ostrzeżeniem nie byłaby wyświetlana jak należy. Jesteśmy gotowi podjąć takie ryzyko.
  4. tak, Wiem, że Microsoft ma "komentarze warunkowe", które można wykorzystać do precyzyjnego wykrywania wersji przeglądarki. IE nie obsługuje już komentarzy warunkowych od IE 10, czyniąc to podejście absolutnie bezużytecznym.
JakieÅ› inne oczywiste problemy?
Author: Alex.K., 2012-06-10

30 answers

To mój ulubiony sposób. Daje maksymalną kontrolę. (Uwaga: polecenia warunkowe są obsługiwane tylko w IE5 - 9.)

Najpierw poprawnie Skonfiguruj swoje klasy ie

<!DOCTYPE html>
<!--[if lt IE 7]> <html class="lt-ie9 lt-ie8 lt-ie7"> <![endif]-->
<!--[if IE 7]>    <html class="lt-ie9 lt-ie8"> <![endif]-->
<!--[if IE 8]>    <html class="lt-ie9"> <![endif]-->
<!--[if gt IE 8]><!--> <html> <!--<![endif]-->    
<head>

Następnie możesz użyć CSS do tworzenia WYJĄTKÓW stylów, lub, jeśli potrzebujesz, możesz dodać prosty JavaScript:

(function ($) {
    "use strict";

    // Detecting IE
    var oldIE;
    if ($('html').is('.lt-ie7, .lt-ie8, .lt-ie9')) {
        oldIE = true;
    }

    if (oldIE) {
        // Here's your JS for IE..
    } else {
        // ..And here's the full-fat code for everyone else
    }

}(jQuery));

Dzięki Paul Irish.

 350
Author: Jezen Thomas,
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-02-19 01:01:32

Return IE version or if not IE return false

function isIE () {
  var myNav = navigator.userAgent.toLowerCase();
  return (myNav.indexOf('msie') != -1) ? parseInt(myNav.split('msie')[1]) : false;
}

Przykład:

if (isIE () == 8) {
 // IE8 code
} else {
 // Other versions IE or not IE
}

Lub

if (isIE () && isIE () < 9) {
 // is IE version less than 9
} else {
 // is IE 9 and later or not IE
}

Lub

if (isIE()) {
 // is IE
} else {
 // Other browser
}
 156
Author: weroro,
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-05-15 13:45:49

Jeśli nikt inny nie dodał metody addEventLister-i używasz poprawnego trybu przeglądarki, możesz sprawdzić IE 8 lub mniej za pomocą

if (window.attachEvent && !window.addEventListener) {
    // "bad" IE
}

Starsze Internet Explorer i attachEvent (MDN)

 117
Author: Andreas,
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-12 12:12:44

Użyj komentarzy warunkowych. Próbujesz wykryć użytkowników IE = 10 i nie-IE) komentarze będą traktowane jako zwykłe komentarze HTML, czyli czym są.

Przykład HTML:

<!--[if lt IE 9]>
WE DON'T LIKE YOUR BROWSER
<![endif]-->

Możesz to również zrobić wyłącznie za pomocą skryptu, jeśli potrzebujesz:

var div = document.createElement("div");
div.innerHTML = "<!--[if lt IE 9]><i></i><![endif]-->";
var isIeLessThan9 = (div.getElementsByTagName("i").length == 1);
if (isIeLessThan9) {
    alert("WE DON'T LIKE YOUR BROWSER");
}
 113
Author: Tim Down,
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-06-27 09:49:32

Aby łatwo wykryć MSIE (v6 - v7 - v8 - v9 - v10 - v11):

if (navigator.userAgent.indexOf('MSIE') !== -1 || navigator.appVersion.indexOf('Trident/') > 0) {
   // MSIE
}
 55
Author: EpokK,
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-01-06 14:11:57

Oto sposób AngularJS sprawdza dla IE

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

if (msie < 9) {
    // code for IE < 9
}
 30
Author: iurii,
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-04 19:10:04

Aby niezawodnie filtrować IE8 i starsze, można użyć sprawdzania obiektów globalnych :

if (document.all && !document.addEventListener) {
    alert('IE8 or lower');
}
 27
Author: Beaudinn Greve,
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-10-05 17:56:02

Ta funkcja zwróci główny numer wersji IE jako liczbę całkowitą, lub undefined jeśli przeglądarka nie jest Internet Explorer. To, podobnie jak wszystkie rozwiązania user agent, jest możliwe do sfingowania user agent (który jest oficjalną cechą IE od wersji 8).

function getIEVersion() {
    var match = navigator.userAgent.match(/(?:MSIE |Trident\/.*; rv:)(\d+)/);
    return match ? parseInt(match[1]) : undefined;
}
 16
Author: Owen,
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-05-23 10:12:34

Wykrywanie IE w JS za pomocÄ… komentarzy warunkowych

// ----------------------------------------------------------
// A short snippet for detecting versions of IE in JavaScript
// without resorting to user-agent sniffing
// ----------------------------------------------------------
// If you're not in IE (or IE version is less than 5) then:
//     ie === undefined
// If you're in IE (>=5) then you can determine which version:
//     ie === 7; // IE7
// Thus, to detect IE:
//     if (ie) {}
// And to detect the version:
//     ie === 6 // IE6
//     ie > 7 // IE8, IE9 ...
//     ie < 9 // Anything less than IE9
// ----------------------------------------------------------

// UPDATE: Now using Live NodeList idea from @jdalton

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

    return v > 4 ? v : undef;

}());
 15
Author: jKey,
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-15 09:11:56

Wykrywanie wersji IE za pomocą wykrywania funkcji (IE6+, przeglądarki przed IE6 są wykrywane jako 6, zwraca null dla przeglądarek innych niż IE):

var ie = (function (){
    if (window.ActiveXObject === undefined) return null; //Not IE
    if (!window.XMLHttpRequest) return 6;
    if (!document.querySelector) return 7;
    if (!document.addEventListener) return 8;
    if (!window.atob) return 9;
    if (!document.__proto__) return 10;
    return 11;
})();

Edit: dla Twojej wygody stworzyłem repo bower/npm: ie-version

Update:

Bardziej zwartą wersję można zapisać w jednej linijce jako:

return window.ActiveXObject === undefined ? null : !window.XMLHttpRequest ? 6 : !document.querySelector ? 7 : !document.addEventListener ? 8 : !window.atob ? 9 : !document.__proto__ ? 10 : 11;
 14
Author: Gabriel Llamas,
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-10-01 05:20:49

To mi pasuje. Używam go jako przekierowania na stronę, która wyjaśnia, dlaczego nie lubimy

<!--[if lt IE 9]>
<meta http-equiv="refresh" content="0;URL=http://google.com">
<![endif]-->
 12
Author: iconMatrix,
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-01-25 19:49:21

Twój kod może wykonać sprawdzenie, ale jak myślałeś, jeśli ktoś spróbuje uzyskać dostęp do twojej strony za pomocą IE v1 lub > v19 nie otrzyma błędu, więc może być bezpieczniej wykonać sprawdzenie z wyrażeniem Regex, jak ten kod poniżej:

var userAgent = navigator.userAgent.toLowerCase();
// Test if the browser is IE and check the version number is lower than 9
if (/msie/.test(userAgent) && 
    parseFloat((userAgent.match(/.*(?:rv|ie)[\/: ](.+?)([ \);]|$)/) || [])[1]) < 9) {
  // Navigate to error page
}
 10
Author: Fong-Wan Chau,
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-01-22 03:52:33

Komentarze warunkowe nie są już obsługiwane w IE od wersji 10, Jak wspomniano na stronie referencyjnej Microsoft .

var ieDetector = function() {
  var browser = { // browser object

      verIE: null,
      docModeIE: null,
      verIEtrue: null,
      verIE_ua: null

    },
    tmp;

  tmp = document.documentMode;
  try {
    document.documentMode = "";
  } catch (e) {};

  browser.isIE = typeof document.documentMode == "number" || eval("/*@cc_on!@*/!1");
  try {
    document.documentMode = tmp;
  } catch (e) {};

  // We only let IE run this code.
  if (browser.isIE) {
    browser.verIE_ua =
      (/^(?:.*?[^a-zA-Z])??(?:MSIE|rv\s*\:)\s*(\d+\.?\d*)/i).test(navigator.userAgent || "") ?
      parseFloat(RegExp.$1, 10) : null;

    var e, verTrueFloat, x,
      obj = document.createElement("div"),

      CLASSID = [
        "{45EA75A0-A269-11D1-B5BF-0000F8051515}", // Internet Explorer Help
        "{3AF36230-A269-11D1-B5BF-0000F8051515}", // Offline Browsing Pack
        "{89820200-ECBD-11CF-8B85-00AA005B4383}"
      ];

    try {
      obj.style.behavior = "url(#default#clientcaps)"
    } catch (e) {};

    for (x = 0; x < CLASSID.length; x++) {
      try {
        browser.verIEtrue = obj.getComponentVersion(CLASSID[x], "componentid").replace(/,/g, ".");
      } catch (e) {};

      if (browser.verIEtrue) break;

    };
    verTrueFloat = parseFloat(browser.verIEtrue || "0", 10);
    browser.docModeIE = document.documentMode ||
      ((/back/i).test(document.compatMode || "") ? 5 : verTrueFloat) ||
      browser.verIE_ua;
    browser.verIE = verTrueFloat || browser.docModeIE;
  };

  return {
    isIE: browser.isIE,
    Version: browser.verIE
  };

}();

document.write('isIE: ' + ieDetector.isIE + "<br />");
document.write('IE Version Number: ' + ieDetector.Version);

Następnie użyj:

if((ieDetector.isIE) && (ieDetector.Version <= 9))
{

}
 8
Author: Arnold.Krumins,
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-27 15:34:50

Dla ie 10 i 11:

Możesz użyć js i dodać klasę w html, aby utrzymać standard komentarzy warunkowych:

  var ua = navigator.userAgent,
      doc = document.documentElement;

  if ((ua.match(/MSIE 10.0/i))) {
    doc.className = doc.className + " ie10";

  } else if((ua.match(/rv:11.0/i))){
    doc.className = doc.className + " ie11";
  }

Lub użyj lib jak bowser:

Https://github.com/ded/bowser

Lub modernizr do wykrywania cech:

Http://modernizr.com/

 5
Author: Liko,
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-05-23 11:47:22

Aby wykryć Internet Explorer 10/11 możesz użyć tego małego skryptu natychmiast po tagu body:

W moim przypadku używam biblioteki jQuery załadowanej w head.

<!DOCTYPE HTML>
<html>
<head>
    <script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
</head>
<body>
    <script>if (navigator.appVersion.indexOf('Trident/') != -1) $("body").addClass("ie10");</script>
</body>
</html>
 3
Author: Brian,
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-08 21:28:17

To zostało odebrane na śmierć, ale to wszystko, czego potrzebujesz.

!!navigator.userAgent.match(/msie\s[5-8]/i)
 3
Author: Timothy Perez,
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-02-17 16:39:59
var Browser = new function () {
    var self = this;
    var nav = navigator.userAgent.toLowerCase();
    if (nav.indexOf('msie') != -1) {
        self.ie = {
            version: toFloat(nav.split('msie')[1])
        };
    };
};


if(Browser.ie && Browser.ie.version > 9)
{
    // do something
}
 2
Author: Berezh,
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-08 20:49:00

Według Microsoft następujące rozwiązanie jest najlepszym rozwiązaniem, jest również bardzo proste:

function getInternetExplorerVersion()
// Returns the version of Internet Explorer or a -1
// (indicating the use of another browser).
{
    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 );
}
 2
Author: AHH,
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-04-17 10:31:40

Zalecam nie przepisywanie tego kodu po raz kolejny. Polecam korzystanie z biblioteki Conditionizr ( http://conditionizr.com/), który jest zdolny do testowania określonych wersji IE, a także innych przeglądarek, systemów operacyjnych, a nawet obecności lub braku wyświetlaczy Retina.

Dołącz Kod tylko do konkretnych testów, których potrzebujesz, a także zyskaj korzyści z testowanej biblioteki, która przeszła wiele iteracji (i która byłaby łatwa aby uaktualnić bez łamania kodu).

Pasuje również do Modernizr, który poradzi sobie ze wszystkimi przypadkami, w których lepiej jest testować konkretną funkcję, a nie konkretną przeglądarkę.

 1
Author: John Munsch,
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-07-02 15:27:32

LubiÄ™ to:

<script>
   function isIE () {
       var myNav = navigator.userAgent.toLowerCase();
       return (myNav.indexOf('msie') != -1) ? parseInt(myNav.split('msie')[1]) : false;
   }    
   var ua = window.navigator.userAgent;
   //Internet Explorer | if | 9-11

   if (isIE () == 9) {
       alert("Shut down this junk! | IE 9");
   } else if (isIE () == 10){
       alert("Shut down this junk! | IE 10");
   } else if (ua.indexOf("Trident/7.0") > 0) {
       alert("Shut down this junk! | IE 11");
   }else{
       alert("Thank god it's not IE!");
   }

</script>
 1
Author: Julio Cesar Boaroli,
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-21 18:23:47

To podejście do wykrywania IE łączy mocne strony i unika słabości odpowiedzi jKey ' a za pomocą komentarzy warunkowych i odpowiedzi Owena za pomocą agentów Użytkownika.

  • podejÅ›cie jKey dziaÅ‚a do wersji 9 i jest odporne na spoofing user agent w IE 8 & 9.
  • PodejÅ›cie Owena może zawieść na IE 5 i 6 (raportowanie 7) i jest podatne na spoofing UA, ale może wykryć wersje IE >= 10(teraz również 12, co potwierdza odpowiedź Owena).

    // ----------------------------------------------------------
    // A short snippet for detecting versions of IE
    // ----------------------------------------------------------
    // If you're not in IE (or IE version is less than 5) then:
    //     ie === undefined
    // Thus, to detect IE:
    //     if (ie) {}
    // And to detect the version:
    //     ie === 6 // IE6
    //     ie > 7 // IE8, IE9 ...
    // ----------------------------------------------------------
    var ie = (function(){
        var v = 3,
            div = document.createElement('div'),
            all = div.getElementsByTagName('i');
    
        while (
            div.innerHTML = '<!--[if gt IE ' + (++v) + ']><i></i><![endif]-->',
            all[0]
        );
        if (v <= 4) { // Check for IE>9 using user agent
            var match = navigator.userAgent.match(/(?:MSIE |Trident\/.*; rv:|Edge\/)(\d+)/);
            v = match ? parseInt(match[1]) : undefined;
        }
        return v;
    }());
    

To może być użyte do Ustawienia użytecznych klas w dokumencie zawierającym wersję IE:

    if (ie) {
        document.documentElement.className += ' ie' + ie;
        if (ie < 9)
            document.documentElement.className += ' ieLT9';
    }

Zauważ, że wykrywa używany tryb zgodności, jeśli IE jest w trybie zgodności. Zauważ również, że wersja IE jest głównie przydatna dla starszych wersji (

 1
Author: jtbr,
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-31 14:17:42

Zrobiłem wygodny Mixin podkreślenia do tego.

_.isIE();        // Any version of IE?
_.isIE(9);       // IE 9?
_.isIE([7,8,9]); // IE 7, 8 or 9?

_.mixin({
  isIE: function(mixed) {
    if (_.isUndefined(mixed)) {
      mixed = [7, 8, 9, 10, 11];
    } else if (_.isNumber(mixed)) {
      mixed = [mixed];
    }
    for (var j = 0; j < mixed.length; j++) {
      var re;
      switch (mixed[j]) {
        case 11:
          re = /Trident.*rv\:11\./g;
          break;
        case 10:
          re = /MSIE\s10\./g;
          break;
        case 9:
          re = /MSIE\s9\./g;
          break;
        case 8:
          re = /MSIE\s8\./g;
          break;
        case 7:
          re = /MSIE\s7\./g;
          break;
      }

      if (!!window.navigator.userAgent.match(re)) {
        return true;
      }
    }

    return false;
  }
});

console.log(_.isIE());
console.log(_.isIE([7, 8, 9]));
console.log(_.isIE(11));
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
 1
Author: danrichards,
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-05-23 20:53:09

Lub po prostu

//   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: 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 isIE = navigator.userAgent.match(/MSIE|Trident|Edge/)
var IEVersion = ((navigator.userAgent.match(/(?:MSIE |Trident.*rv:|Edge\/)(\d+(\.\d+)?)/)) || []) [1]
 1
Author: Giacomo,
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-04-08 17:57:19

Najbardziej wszechstronny skrypt JS jaki znalazłem do sprawdzenia wersji IE to http://www.pinlady.net/PluginDetect/IE/. cała biblioteka znajduje się w http://www.pinlady.net/PluginDetect/Browsers/.

W IE10 polecenia warunkowe nie są już obsługiwane.

W IE11, user agent nie zawiera już MSIE. Ponadto korzystanie z agenta użytkownika nie jest niezawodne, ponieważ można go zmodyfikować.

Za pomocą skryptu PluginDetect JS można wykryć dla IE i wykryć dokładne wersje za pomocą bardzo specyficznego i dobrze spreparowanego kodu, który dotyczy konkretnych wersji IE. Jest to bardzo przydatne, gdy zależy Ci dokładnie, z jaką wersją przeglądarki pracujesz.

 0
Author: PressingOnAlways,
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-01-17 21:08:00

Zdaję sobie sprawę, że jestem trochę spóźniony na imprezę, ale sprawdzałem prosty, jednowierszowy sposób, aby przekazać opinię na temat tego, czy przeglądarka to IE i jaka wersja od 10 w dół. Nie zakodowałem tego dla wersji 11, więc być może potrzebna będzie do tego mała poprawka.

Jednak jest to kod, działa jako obiekt, który ma właściwość i metodę i opiera się na wykrywaniu obiektów, a nie na skrobaniu obiektu nawigatora (który jest masowo wadliwy, jak to może być spoofed).

var isIE = { browser:/*@cc_on!@*/false, detectedVersion: function () { return (typeof window.atob !== "undefined") ? 10 : (typeof document.addEventListener !== "undefined") ? 9 : (typeof document.querySelector !== "undefined") ? 8 : (typeof window.XMLHttpRequest !== "undefined") ? 7 : (typeof document.compatMode !== "undefined") ? 6 : 5; } };

Użycie jest isIE.browser właściwością, która zwraca wartość logiczną i opiera się na komentarzach warunkowych metody isIE.detectedVersion(), która zwraca liczbę od 5 do 10. Zakładam, że cokolwiek niższe niż 6 i jesteś na poważnym terytorium starej szkoły i będzie coś bardziej beefy niż jeden liniowiec i cokolwiek wyższe niż 10 i jesteś w nowszym terytorium. Czytałem coś o IE11 nie obsługującym komentarzy warunkowych ale nie do końca zbadałem, czyli może na później.

W każdym razie, jak to jest, a dla jednego linera, obejmie podstawy przeglądarki IE i wykrywania wersji. Jest daleki od ideału, ale jest mały i łatwo go zmienić.

Tylko dla odniesienia, a jeśli ktoś ma jakiekolwiek wątpliwości, jak faktycznie wdrożyć ten warunek, powinien pomóc następujący warunek.

var isIE = { browser:/*@cc_on!@*/false, detectedVersion: function () { return (typeof window.atob !== "undefined") ? 10 : (typeof document.addEventListener !== "undefined") ? 9 : (typeof document.querySelector !== "undefined") ? 8 : (typeof window.XMLHttpRequest !== "undefined") ? 7 : (typeof document.compatMode !== "undefined") ? 6 : 5; } };

/* testing IE */

if (isIE.browser) {
  alert("This is an IE browser, with a detected version of : " + isIE.detectedVersion());
}
 0
Author: Ric Paton,
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-18 10:30:28

Wykrywanie IE i jego wersji nie może być łatwiejsze, a wszystko czego potrzebujesz to trochę natywnego / waniliowego Javascript:

var uA = navigator.userAgent;
var browser = null;
var ieVersion = null;

if (uA.indexOf('MSIE 6') >= 0) {
    browser = 'IE';
    ieVersion = 6;
}
if (uA.indexOf('MSIE 7') >= 0) {
    browser = 'IE';
    ieVersion = 7;
}
if (document.documentMode) { // as of IE8
    browser = 'IE';
    ieVersion = document.documentMode;
}

I jest to sposób użycia:

if (browser == 'IE' && ieVersion <= 9) 
    document.documentElement.className += ' ie9-';

.

Działa we wszystkich wersjach IE, w tym w wyższych wersjach w widoku/trybie niższej zgodności, a {[2] } jest własnością IE.

 0
Author: Frank Conijn,
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-18 14:27:32

Jeśli chcesz usunąć wersję przeglądarki IE, możesz wykonać poniższy kod. Ten kod działa dobrze dla wersji IE6 do IE11

<!DOCTYPE html>
<html>
<body>

<p>Click on Try button to check IE Browser version.</p>

<button onclick="getInternetExplorerVersion()">Try it</button>

<p id="demo"></p>

<script>
function getInternetExplorerVersion() {
   var ua = window.navigator.userAgent;
        var msie = ua.indexOf("MSIE ");
        var rv = -1;

        if (msie > 0 || !!navigator.userAgent.match(/Trident.*rv\:11\./))      // If Internet Explorer, return version number
        {               
            if (isNaN(parseInt(ua.substring(msie + 5, ua.indexOf(".", msie))))) {
                //For IE 11 >
                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);
                        alert(rv);
                    }
                }
                else {
                    alert('otherbrowser');
                }
            }
            else {
                //For < IE11
                alert(parseInt(ua.substring(msie + 5, ua.indexOf(".", msie))));
            }
            return false;
        }}
</script>

</body>
</html>
 0
Author: Nimesh,
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-15 06:44:07

Uruchomienie okna IE10 będzie automatyczną aktualizacją do IE11+ i będzie znormalizowane W3C

Teraz nie musimy wspierać IE8 -

    <!DOCTYPE html>
    <!--[if lt IE 9]><html class="ie ie8"><![endif]-->
    <!--[if IE 9]><html class="ie ie9"><![endif]-->
    <!--[if (gt IE 9)|!(IE)]><!--><html><!--<![endif]-->
    <head>
        ...
        <!--[if lt IE 8]><meta http-equiv="Refresh" content="0;url=/error-browser.html"><![endif]--
        ...
    </head>
 0
Author: xicooc,
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-01-07 03:36:10
var isIE9OrBelow = function()
{
   return /MSIE\s/.test(navigator.userAgent) && parseFloat(navigator.appVersion.split("MSIE")[1]) < 10;
}
 0
Author: xicooc,
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-24 02:07:41
if (!document.addEventListener) {
    // ie8
} else if (!window.btoa) {
    // ie9
}
// others
 0
Author: Bruce,
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-11-12 06:56:56