简体   繁体   中英

detect Internet Explorer (working with IE10+ too!)

Conditional comments have been deprecated since IE10 which is breaking some legacy code used to detect whether the current web browser is IE or not. See https://gist.github.com/padolsey/527683

I search for a solution that works for ALL versions of Internet Explorer (Not only IE9 and below).

Thanks

Following a comment from "ecstaticpeon" on https://gist.github.com/padolsey/527683 , I found that this works.

try it yourself on http://jsfiddle.net/P5z4N/4/

var ie_version = (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;
}());
/*@cc_on
if (typeof(ie_version) == 'undefined') {
    ie_version = parseInt(@_jscript_version);
}
@*/

The below javascript also seems to work:

Try it on http://jsfiddle.net/e8G3S/1/

// 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 displayAlert(){
  var msg = "You're not using Internet Explorer.";
  var ver = getInternetExplorerVersion();
  if ( ver > -1 ){
    if ( ver <= 8.0 ){
      msg = "You're using Internet Explorer 8 or below" ;
    }
    else if ( ver >= 9.0 && ver < 10.0 ){
      msg = "You're using IE 9 or above";
    }
    else{
      msg = "You're using IE 10 or above"; 
    }
  }
  alert( msg );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM