252

Internet Explorerv9 より前のバージョンの を使用している場合、Web サイトのユーザーをエラー ページにバウンスさせたいと考えています。サポートに時間とお金を費やすだけの価値はありませんIE pre-v9。他のすべての非 IE ブラウザーのユーザーは問題なく、バウンスされるべきではありません。提案されたコードは次のとおりです。

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

このコードでうまくいくでしょうか?

おそらく私のところに来るであろういくつかのコメントを避けるために:

  1. はい、ユーザーが自分の文字列を偽造できることを知っていuseragentます。私は気にしません。
  2. はい、プログラミングのプロがブラウザーの種類ではなく機能のサポートを嗅ぎ分けることを好むことは知っていますが、この場合、このアプローチは意味がないと思います。IE 以外のすべての (関連する) ブラウザーが必要な機能をサポートしていて、すべてのpre-v9 IEブラウザーがサポートしていないことは既にわかっています。サイト全体で機能ごとにチェックするのは無駄です。
  3. はい、誰かがIE v1(または >= 20) を使用してサイトにアクセスしようとすると、'badBrowser' が true に設定されず、警告ページが正しく表示されないことがわかっています。それは私たちが喜んで引き受けるリスクです。
  4. はい、Microsoft には、ブラウザのバージョンを正確に検出するために使用できる「条件付きコメント」があることを知っています。IE は の時点で条件付きコメントをサポートしなくなったためIE 10、このアプローチはまったく役に立たなくなりました。

他に注意すべき明らかな問題はありますか?

4

37 に答える 37

358

これは私の好みの方法です。最大限のコントロールを提供します。(注: 条件文は IE5 ~ 9 でのみサポートされています。)

最初に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>

次に、CSS を使用してスタイルの例外を作成するか、必要に応じて簡単な 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));

ポール・アイリッシュに感謝します。

于 2012-06-09T22:38:20.997 に答える
118

条件付きコメントを使用します。IE < 9 のユーザーを検出しようとしており、条件付きコメントはそれらのブラウザーで機能します。他のブラウザー (IE >= 10 および非 IE) では、コメントは通常の HTML コメントとして扱われます。

HTML の例:

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

必要に応じて、純粋にスクリプトを使用してこれを行うこともできます。

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");
}
于 2012-06-09T23:03:19.773 に答える
117

誰もaddEventLister-method を追加しておらず、正しいブラウザ モードを使用している場合は、次のコマンドで IE 8 以下を確認できます。

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

従来の Internet Explorer と attachEvent (MDN)

于 2012-06-09T22:34:49.467 に答える
61

MSIE (v6 - v7 - v8 - v9 - v10 - v11) を簡単に検出するには:

if (navigator.userAgent.indexOf('MSIE') !== -1 || navigator.appVersion.indexOf('Trident/') > 0) {
   // MSIE
}
于 2013-12-05T21:58:05.903 に答える
28

IE8 以前を確実にフィルタリングするには、グローバル オブジェクトのチェックを使用できます。

if (document.all && !document.addEventListener) {
    alert('IE8 or lower');
}
于 2014-06-25T12:27:45.863 に答える
21

機能検出を使用した IE バージョンの検出 (IE6+、IE6 より前のブラウザーは 6 として検出され、IE 以外のブラウザーの場合は null を返します):

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

編集: 便宜上、bower/npm リポジトリを作成しました: ie-version

アップデート:

よりコンパクトなバージョンは、次のように 1 行で記述できます。

return window.ActiveXObject === undefined ? null : !window.XMLHttpRequest ? 6 : !document.querySelector ? 7 : !document.addEventListener ? 8 : !window.atob ? 9 : !document.__proto__ ? 10 : 11;
于 2014-09-28T07:48:42.533 に答える
16

条件付きコメントを使用して JS で IE を検出する

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

}());
于 2013-08-15T09:11:56.300 に答える
13

これは私にとってはうまくいきます。私はこれを、なぜ IE9 よりも嫌いなのかを説明するページへのリダイレクトとして使用し、私たちが好むブラウザーへのリンクを提供します。

<!--[if lt IE 9]>
<meta http-equiv="refresh" content="0;URL=http://google.com">
<![endif]-->
于 2013-01-25T19:49:21.637 に答える
10

コードでチェックを実行できますが、ご想像のとおり、誰かが IE v1 または > v19 を使用してページにアクセスしようとしてもエラーは発生しないため、以下のコードのように正規表現でチェックを行う方が安全かもしれません。

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
}
于 2012-06-09T22:25:10.697 に答える
3
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
}
于 2013-12-08T20:49:00.533 に答える
2

Microsoftによると、以下が最善の解決策であり、非常に簡単です。

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 );
}
于 2014-04-17T10:31:40.310 に答える
1

IE のバージョンを確認するために見つけた最も包括的な JS スクリプトはhttp://www.pinlady.net/PluginDetect/IE/です。ライブラリ全体はhttp://www.pinlady.net/PluginDetect/Browsers/にあります。

IE10 では、条件ステートメントはサポートされなくなりました。

IE11 では、ユーザー エージェントに MSIE が含まれなくなりました。また、ユーザー エージェントの使用は、変更できるため信頼性がありません。

PluginDetect JS スクリプトを使用すると、IE を検出し、特定の IE バージョンを対象とする非常に具体的で巧妙に作成されたコードを使用して正確なバージョンを検出できます。これは、使用しているブラウザーのバージョンを正確に気にする場合に非常に便利です。

于 2014-01-17T21:08:00.510 に答える
1

私はそれが好きです:

<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>
于 2015-08-21T18:23:47.207 に答える
1

IE を検出するこのアプローチは、条件付きコメントを使用する jKey の回答とユーザー エージェントを使用する Owen の回答の長所を組み合わせ、短所を回避します。

  • jKey のアプローチはバージョン 9 まで機能し、IE 8 および 9 でのユーザー エージェント スプーフィングの影響を受けません。
  • Owen のアプローチは IE 5 および 6 (報告 7) で失敗する可能性があり、UA スプーフィングの影響を受けやすいですが、IE バージョン >= 10 を検出できます (現在、Owen の回答より後の 12 も含まれています)。

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

これを使用して、IE バージョンを含むドキュメントに有用なクラスを設定できます。

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

IE が互換モードの場合、使用されている互換モードを検出することに注意してください。また、IE のバージョンは古いバージョン (10 未満) で最も役立つことに注意してください。バージョンが高いほど標準に準拠しているため、代わりに modernizr.js などを使用して機能を確認することをお勧めします。

于 2015-08-31T14:17:42.470 に答える
1

このコードを何回も書き直さないことをお勧めします。特定の IE バージョンだけでなく、他のブラウザー、オペレーティング システム、さらには Retina ディスプレイの有無をテストできるConditionizr ライブラリ ( http://conditionizr.com/ ) を使用することをお勧めします。

必要な特定のテストのコードのみを含めると、多くの反復を経てテストされたライブラリの利点も得られます (コードを壊さずに簡単にアップグレードできます)。

また、特定のブラウザーではなく特定の機能をテストする方が適切なすべてのケースを処理できる Modernizr とうまくかみ合います。

于 2015-07-02T15:27:32.147 に答える
0

IE とそのバージョンの検出は非常に簡単で、必要なのはネイティブ/バニラ 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;
}

そして、これはそれを使用する方法です:

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

.

互換性の低いビュー/モードの上位バージョンを含むすべての IE バージョンで動作し、documentModeIE 独自のものです。

于 2014-06-18T13:45:46.467 に答える
0
if (!document.addEventListener) {
    // ie8
} else if (!window.btoa) {
    // ie9
}
// others
于 2015-11-12T06:56:56.930 に答える
0

ここでのパーティーに少し遅れたことに気付きましたが、ブラウザーが IE であるかどうか、および 10 からどのバージョンであったかについてフィードバックを提供するための簡単な 1 行の方法を調べていました。バージョン 11 ではこれをコーディングしていないので、おそらく少し修正が必要になるでしょう。

ただし、これはコードであり、プロパティとメソッドを持ち、ナビゲーター オブジェクトをスクレイピングするのではなく、オブジェクト検出に依存するオブジェクトとして機能します (スプーフィングされる可能性があるため、大きな欠陥があります)。

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

使用法は、ブール値を返すプロパティであり、5 から 10 の間の数値を返すisIE.browserメソッドの条件付きコメントに依存しています。 isIE.detectedVersion()1 ライナーで 10 を超えると、新しい領域に入ります。IE11 が条件付きコメントをサポートしていないことについて読んだことがありますが、完全には調査していません。

とにかく、一言で言えば、IE ブラウザーの基本とバージョン検出について説明します。完璧にはほど遠いですが、小さくて簡単に修正できます。

参考までに、これを実際に実装する方法について疑問がある場合は、次の条件が役立ちます。

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());
}
于 2014-06-18T10:30:28.093 に答える
0

IE ブラウザのバージョンを削除する必要がある場合は、以下のコードに従ってください。このコードは、バージョン IE6 から 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>
于 2014-10-15T06:33:56.380 に答える
0

以下のコードペンは、すべての場合 (IE<=9、IE10、IE11、および IE/Edge) で IE のバージョンを識別します。

function detectIE() {
    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 (IE 12+) => return version number
        return parseInt(ua.substring(edge + 5, ua.indexOf('.', edge)), 10);
    }
    // other browser
    return false;
}

参照: https://codepen.io/gapcode/pen/vEJNZN

于 2016-09-06T07:04:56.377 に答える
0

Window runs IE10 は IE11+ に自動更新され、W3C で標準化されます

現在、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>
于 2015-01-07T03:36:10.830 に答える
0

それは私を助けました

function IsIE8Browser() {
  var rv = -1;
  var ua = navigator.userAgent;
  var re = new RegExp("Trident\/([0-9]{1,}[\.0-9]{0,})");
  if (re.exec(ua) != null) {
    rv = parseFloat(RegExp.$1);
  }
  return (rv == 4);
}
于 2018-01-30T07:30:50.083 に答える
-1

JQuery の使用:

http://tanalin.com/en/articles/ie-version-js/

C# の使用:

var browser = Request.Browser.Browser;
于 2014-11-28T13:20:15.347 に答える