Detection of Internet Explorer 8 emulation mode via Javascript

Today at work we had a strange Javascript error that only happened on Internet Explorer 8, which we set to IE7 emulation with the special EmulateIE7 meta tag.

After some digging we found that the site was rendering (correctly) in IE7 Mode, but our javascript Browser detection library was identifying it (incorrectly) as IE8, because of relying just on User-Agent detection.

When using javascript there is not many options: Check the UA, check some basic capabilities like resolution, presence/absence of certain functions and objects...

I really don't know why Microsoft didn't just override the UA string if detected the meta tag in emulation mode, but I won't enter into details.

A basic IE8 detection via javascript might be the following:

isIE8 = (/MSIE (8+\.\d+);/.test(navigator.userAgent));

But as I said, this is not enough, so after searching a bit, I found how to check via Javascript the document mode (UPDATE: sorry but original link no longer exists) and thus capture the real state of IE8. The following check should be done after the previous UA check:

if (isIE8) {
if (document.documentMode === 7 || document.compatMode == "CSS1Compat") {
isIE8 = false;

// Probably also set isIE7 = true or something similar
}
}

I've only used IE8 as an example, but as IE9 "evolves" this concept should be compatible, but being still in beta is better to wait (also is much better to not emulate anything and instead use the finally standardized JS and CSS).

Update: Seems that the document.compatMode can misguide in some cases. As it was done for IE8 RC can be safely removed:

if (isIE8) {
if (document.documentMode === 7) {
isIE8 = false;

// Probably also set isIE7 = true or something similar
}
}

Detection of Internet Explorer 8 emulation mode via Javascript published @ . Author: