Programing

사용자가 IE를 사용하고 있는지 확인

lottogame 2020. 3. 4. 08:07
반응형

사용자가 IE를 사용하고 있는지 확인


특정 클래스가있는 div를 클릭하여 아래와 같은 함수를 호출합니다.

사용자가 Internet Explorer를 사용하는 경우 기능을 시작할 때 확인할 수 있고 다른 브라우저를 사용하는 경우 IE 사용자에게만 실행되도록 중단 / 취소 할 수있는 방법이 있습니까? 여기에있는 사용자는 모두 IE8 이상 버전이므로 IE7 이하 버전을 다루지 않아도됩니다.

그들이 사용하는 브라우저를 알 수 있다면 훌륭하지만 필수는 아닙니다.

기능 예 :

$('.myClass').on('click', function(event)
{
    // my function
});

아래 JavaScript 방법을 사용하십시오.

function msieversion() 
{
    var ua = window.navigator.userAgent;
    var msie = ua.indexOf("MSIE ");

    if (msie > 0) // If Internet Explorer, return version number
    {
        alert(parseInt(ua.substring(msie + 5, ua.indexOf(".", msie))));
    }
    else  // If another browser, return 0
    {
        alert('otherbrowser');
    }

    return false;
}

아래의 Microsoft 지원 사이트에서 자세한 내용을 확인할 수 있습니다.

스크립트에서 브라우저 버전을 확인하는 방법

업데이트 : (IE 11 지원)

function msieversion() {

    var ua = window.navigator.userAgent;
    var msie = ua.indexOf("MSIE ");

    if (msie > 0 || !!navigator.userAgent.match(/Trident.*rv\:11\./))  // If Internet Explorer, return version number
    {
        alert(parseInt(ua.substring(msie + 5, ua.indexOf(".", msie))));
    }
    else  // If another browser, return 0
    {
        alert('otherbrowser');
    }

    return false;
}

Internet Explorer 12 이상 (일명 Edge)부터 사용자 에이전트 문자열 이 다시 한 번 변경되었습니다.

/**
 * detect IE
 * returns version of IE or false, if browser is not Internet Explorer
 */
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;
}

샘플 사용법 :

alert('IE ' + detectIE());

IE 10의 기본 문자열 :

Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; Trident/6.0)

IE 11의 기본 문자열 :

Mozilla/5.0 (Windows NT 6.3; Trident/7.0; rv:11.0) like Gecko 

IE 12의 기본 문자열 (일명 Edge) :

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의 기본 문자열 (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 

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 

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 

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 

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 

Edge 18의 기본 문자열 (삽입 미리보기) :

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 

CodePen에서 테스트 :

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


브라우저가 IE인지 아닌지 알고 싶다면 다음과 같이하십시오.

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
}

업데이트 1 : 더 나은 방법

나는 이것을 추천합니다. 여전히 읽을 수 있고 코드가 훨씬 적습니다. :)

var ua = window.navigator.userAgent;
var isIE = /MSIE|Trident/.test(ua);

if ( isIE ) {
  //IE specific code goes here
}

단축 답변에 대한 의견에 JohnnyFun에게 감사드립니다 :)

업데이트 2 : CSS에서 IE 테스트

먼저 가능한 경우 @supports브라우저가 특정 CSS 기능을 지원하는지 확인하기 위해 JS 대신 명령문 을 사용해야 합니다.

.element {
  /* styles for all browsers */
}

@supports (display: grid) {
  .element {
    /* styles for browsers that support display: grid */
  }
}

(IE는 전혀 지원하지 않으며 명령문 @supports안에 배치 된 스타일은 무시합니다 @supports.)

문제를 해결할 수없는 경우 @supports다음을 수행하십시오.

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

(참고 : classListJS에 비교적 익숙하지 않으며 IE 브라우저 중 IE11에서만 작동한다고 생각합니다. IE10에서도 가능합니다.)

프로젝트에서 SCSS (Sass)를 사용하는 경우 다음과 같이 단순화 할 수 있습니다.

/* SCSS (Sass) */

.element {
  /* styles that apply everywhere */

  .ie & {
    /* styles that only apply in IE */
  }
}

업데이트 3 : Microsoft Edge 추가

Microsoft Edge를 목록에 추가하려면 다음을 수행하십시오. 그러나 Edge는 IE보다 훨씬 유능한 브라우저이므로 권장하지 않습니다.

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

if ( isIE ) {
  //IE & Edge specific code goes here
}

true모든 버전의 Internet Explorer에 대해 다음을 반환 합니다.

function isIE(userAgent) {
  userAgent = userAgent || navigator.userAgent;
  return userAgent.indexOf("MSIE ") > -1 || userAgent.indexOf("Trident/") > -1 || userAgent.indexOf("Edge/") > -1;
}

userAgent매개 변수는 선택 사항이며, 브라우저의 사용자 에이전트에 대한 기본값.


네비게이터 객체를 사용하여 사용자 탐색기를 감지 할 수 있으며 jquery가 필요하지 않습니다.

<script type="text/javascript">

if (/MSIE (\d+\.\d+);/.test(navigator.userAgent) || navigator.userAgent.indexOf("Trident/") > -1 ){ 

 // do stuff with ie-users
}

</script>

http://www.javascriptkit.com/javatutors/navigator.shtml


이것이 Angularjs 팀이 수행하는 방식입니다 ( 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;

그런 다음 코드를 사용하여 여러 줄로 흩어져 있습니다.

if (event === 'input' && msie <= 11) return false;

if (enabled && msie < 8) {

위의 답변을 사용하여; 단순 및 요약 반환 부울 ​​:

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


방법 01 :
$ .browser는 jQuery 버전 1.3에서 더 이상 사용되지 않으며 1.9에서 제거되었습니다.

if ( $.browser.msie) {
  alert( "Hello! This is IE." );
}

방법 02 :
조건부 주석 사용

<!--[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]>

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

방법 04 :
JavaScript / 수동 감지 사용

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

 }());

참조 링크


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

    return ie > -1;
}

브라우저가 IE11 이상인지 확인하고 싶었습니다.

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

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

브라우저가 IE인지 아닌지를 감지하는 또 다른 간단한 (아직 사람이 읽을 수있는) 함수는 전혀 무시하지 않는 Edge를 무시합니다.

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

useragent를 사용하지 않으려면 브라우저가 IE인지 확인하기 위해이 작업을 수행 할 수도 있습니다. 주석 처리 된 코드는 실제로 IE 브라우저에서 실행되며 "false"를 "true"로 바꿉니다.

var isIE = /*@cc_on!@*/false;
if(isIE){
    //The browser is IE.
}else{
    //The browser is NOT IE.
}   

나는 이것이 오래된 질문이라는 것을 알고 있지만, 누군가가 그것을 다시 만나서 IE11 감지에 문제가있는 경우, 모든 현재 버전의 IE에 대한 작동 솔루션입니다.

var isIE = false;
if (navigator.userAgent.indexOf('MSIE') !== -1 || navigator.appVersion.indexOf('Trident/') > 0) {
    isIE = true;   
}

나는 이것을 사용했다

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

여기에 많은 답변이 있으며 입력 내용을 추가하고 싶습니다. IE 11은 flexbox와 관련된 엉덩이였습니다 ( 여기의 모든 문제와 불일치 참조 ). 사용자가 IE 브라우저 (11 이상)를 사용하고 있지만 Edge를 제외하고 있는지 확인하는 쉬운 방법이 실제로 필요했습니다. Edge는 실제로 꽤 좋은.

여기에 주어진 대답을 바탕으로 전역 부울 변수를 반환하는 간단한 함수를 작성했습니다. 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!");
}

이렇게하면 조회를 한 번만 수행하면되며 각 함수 호출에서 결과를 가져 오는 대신 결과를 변수에 저장합니다. (내가 아는 한 사용자 에이전트가 DOM과 관련이 없으므로이 코드를 실행할 준비가 된 문서를 기다릴 필요조차 없습니다.)


jquery 버전> = 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;
}

jQuery 버전 <1.9를 사용하는 경우 (jQuery 1.9에서 $ .browser가 제거됨) 대신 다음 코드를 사용하십시오.

$('.myClass').on('click', function (event) {
    if ($.browser.msie) {
        alert($.browser.version);
    }
});

@SpiderCode의 솔루션은 IE 11에서 작동하지 않습니다. 다음은 특정 기능에 대한 브라우저 감지가 필요한 코드에서 사용한 최고의 솔루션입니다.

이 변경 목록에 따르면 IE11은 더 이상 MSIE로보고하지 않습니다. 오 탐지를 피하기위한 것입니다.

만약 당신이 정말로 IE를 알고 싶다면 당신이 할 수있는 것은 navigator.appName이 (테스트되지 않은) Netscape를 반환한다면 사용자 에이전트에서 Trident / 문자열을 탐지하는 것입니다;

이 답변 덕분에

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

아래는 인터넷 검색을하는 동안 우아한 방법을 찾았습니다.

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

문자열 'MSIE'가 -1을 반환하지만 'Trident'와 일치하는 문제를 해결하기 위해 SpiderCode의 답변으로 업데이트하십시오. NAN을 반환했지만 이제는 해당 버전의 IE에 대해 11을 반환합니다.

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

모든 Internet Explorer (최종 테스트 된 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>

여기를 참조하십시오 https://jsfiddle.net/v7npeLwe/


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

콘솔에 결과가 표시되어야합니다. 크롬 검사를 사용하십시오.


이 코드를 문서 준비 기능에 넣고 인터넷 탐색기에서만 트리거합니다. Internet Explorer 11에서 테스트되었습니다.

var ua = window.navigator.userAgent;
ms_ie = /MSIE|Trident/.test(ua);
if ( ms_ie ) {
    //Do internet explorer exclusive behaviour 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;
    }
}

이것은 IE 11 버전에서만 작동합니다.

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


또는이 정말 짧은 버전은 브라우저가 Internet Explorer 인 경우 true를 반환합니다.

function isIe() {
    return window.navigator.userAgent.indexOf("MSIE ") > 0
        || !!navigator.userAgent.match(/Trident.*rv\:11\./);
}

Internet Explorer 또는 Edge 버전을 감지하는 JavaScript 기능

function ieVersion(uaString) {
  uaString = uaString || navigator.userAgent;
  var match = /\b(MSIE |Trident.*?rv:|Edge\/)(\d+)/.exec(uaString);
  if (match) return parseInt(match[2])
}

이렇게 해보십시오

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

}

$.browser이름, 공급 업체 및 버전 정보를 얻는 데 사용할 수 있습니다 .

http://api.jquery.com/jQuery.browser/를 참조하십시오.

참고 URL : https://stackoverflow.com/questions/19999388/check-if-user-is-using-ie



반응형