检查用户是否使用IE

问题描述 投票:308回答:29

我通过点击某个类的div来调用下面的函数。

有没有办法在用户使用Internet Explorer时检查何时启动该功能,如果他们使用其他浏览器就中止/取消它以便它只为IE用户运行?这里的用户都将使用IE8或更高版本,因此我不需要涵盖IE7及更低版本。

如果我可以告诉他们使用哪个浏览器那将是很好但不是必需的。

功能示例:

$('.myClass').on('click', function(event)
{
    // my function
});
javascript jquery internet-explorer browser-detection
29个回答
401
投票

使用以下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支持站点下方找到详细信息:

How to determine browser version from script

更新:(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;
}

4
投票

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

4
投票

另一个简单(但人类可读)的功能来检测浏览器是否是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);
}

3
投票

如果您不想使用useragent,您也可以执行此操作以检查浏览器是否为IE。评论代码实际上在IE浏览器中运行,并将“false”变为“true”。

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

3
投票

我知道这是一个老问题,但是如果有人再遇到它并且在检测IE11时遇到问题,这里是所有当前版本IE的工作解决方案。

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

3
投票

我用过这个

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

2
投票

如果您使用的是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);
    }
});

1
投票

@ SpiderCode的解决方案不能与IE 11一起使用。这是我今后在代码中使用的最佳解决方案,我需要针对特定​​功能进行浏览器检测。

IE11不再报告为MSIE,根据此更改列表,它是故意避免错误检测。

如果你真的想知道它是什么你可以做的IE是如果navigator.appName返回Netscape,检测用户代理中的Trident /字符串,类似(未经测试);

感谢this answer

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

1
投票

下面我发现谷歌搜索的优雅方式---

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

1
投票

这里有很多答案,我想补充一下我的意见。 IE 11是关于flexbox的这样一个屁股(查看它的所有问题和不一致的here)我真的需要一个简单的方法来检查用户是否使用任何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无关。)


1
投票

更新SpiderCode的答案,解决字符串'MSIE'返回-1但匹配'Trident'的问题。它曾用于返回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;
       }
    }

509
投票

从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的默认字符串(aka 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 

边缘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 

边缘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 

边缘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 

边缘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


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

0
投票

您可以检测所有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/


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

您应该在控制台中看到结果,请使用chrome Inspect。


0
投票

我已将此代码放在文档就绪函数中,它只在Internet Explorer中触发。在Internet Explorer 11中测试。

var ua = window.navigator.userAgent;
ms_ie = /MSIE|Trident/.test(ua);
if ( ms_ie ) {
    //Do internet explorer exclusive behaviour here
}

0
投票

我认为它会帮助你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;
    }
}

0
投票

这仅适用于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);


0
投票

或者这个真正的短版本,如果浏览器是Internet Explorer则返回true:

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

0
投票

用于检测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])
}

-1
投票

尝试这样做

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

}

-3
投票

您可以使用$.browser获取名称,供应商和版本信息。

http://api.jquery.com/jQuery.browser/


90
投票

只是添加马里奥非常有用的答案。

如果您只想知道浏览器是否为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
}

更新

我现在推荐这个。它仍然非常易读,代码少得多:)

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

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

感谢JohnnyFun对缩短答案的评论:)


45
投票

这会为任何版本的Internet Explorer返回true

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

userAgent参数是可选的,默认为浏览器的用户代理。


26
投票

您可以使用导航器对象来检测用户导航器,您不需要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


20
投票

这就是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) {

10
投票

使用上面的答案;简单和精简返回布尔值:

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


9
投票

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

 }());

Reference Link


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

    return ie > -1;
}
© www.soinside.com 2019 - 2024. All rights reserved.