简体   繁体   中英

Detecting IE8 reliably using javascript

I have written a web app that requires IE version 8 (or higher presumably). If I run IE8 on a clean windows install on a VM it reports 'MSIE 8.0' as a user agent when queried with navigator.userAgent in javascript. But on a colleagues windows 7 machine his IE reports version 8 in the Help|About window, but the user agent string is 'MSIE 7.0'.

I figure that somewhere on his machine there is a setting that's telling IE to spoof the previous version, some kind of compatibility setting I presume, but for the life of me I can't find it. I'm not setting up quirksmode or IE7 compatibility mode from my end.

<meta http-equiv="X-UA-Compatible" content="IE=8">
<script type="text/javascript">
var is_ie8_or_newer = false;
</script>
<!--[if gte IE 8]>
<script type="text/javascript">
is_ie8_or_newer = true;
</script>
<![endif]-->

The user agent is not a sensible or reliable way of determining the browser version. Why don't you look for the presence of the feature you require by making it IE8 only and use that? That is a much more reliable method.

The most entertaining trick I've seen — without having any idea of how efficient it is — is to leverage the IE conditional comment feature dynamically . To do that, your code takes a hidden <div> or a <div> in a document fragment, or whatever, and inserts into it some HTML surrounded by a conditional comment coded to check for a specific browser version:

var dummy = document.getElementById('dummy');
dummy.innerHTML = '<!' + '--[if IE 8]>x<![endif]-->';
var isIE8 = dummy.innerHTML === 'x';

IE8 can show a little button next to the URL box that switches the browser between IE7 mode and IE8 mode. You can open up the "Developer Tools" and that'll tell you what the current setting is.

Could you use conditional comments?

<script>
  var is_ie8 = false;
</script>
<!--[if IE 8]>
  <script>
    is_ie8 = true;
  </script>
<![endif]-->

Found this sweet function on GIT (in the comments) :

function getIEVersion() 
{    
    var v = 3, div = document.createElement('div'), a = div.all || [];
    while (div.innerHTML = '<!--[if gt IE '+(++v)+']><br><![endif]-->', a[0]); 
    return v > 4 ? v : !v;    
};

http://www.modernizr.com/

It should detect such issues. Alternatively, I'm not sure but IE 8 might switch its User-Agent tag in 'Compatibility Mode'.

The only way I can figure out how to get my version of IE8 to say that it is IE7 is to enable Compatibility View. See http://blogs.msdn.com/b/ie/archive/2008/08/27/introducing-compatibility-view.aspx

Turns out his browser was set to display all 'intranet sites' in compatibility mode. Also, yes, compatibility mode changes the user agent string.

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