0yhkfg
Last Updated: February 25, 2016
·
1.552K
· technotronicoz

Test for IE8/9 Compatibility View

Having to support IE8 can be a big drag, but having to support IE8 in Compatibility View can be even more so. On a recent project I was asked if I could provide support for Compatibility View, to which my initial answer was a bit unsure as I had no clue how to determine when the browser was in Compatibility View. After a bit of searching the inter-webs and not finding much, I decided to spin up my VMs and put together a spreadsheet with each browser version's user agent string and documentMode. I ran each browser through compatibility view and through each browser version that was available in F12. After an hour or two of digging through the numbers, I figured out how one can reliably test for Compatibility View.

Trident versions are specific to the true browser version, IE10 runs Trident6, IE9 runs Trident5, IE8 runs Trident4. This is the important value. Our next important value is MSIE7 in the user agent string. Regardless of the version of IE, when in Compatibility View, the browser always reports itself as MSIE7.0 in the user agent string. By testing for the existence of MSIE7.0 and comparing that to the version of Trident, we can accurately determine when the browser is in old school mode (ie Compatibility View).

By taking our newfound logic and applying it to Modernizr's addTest API, we can have a great little solution in place. Below is a link to my Github repo along with the code (un-minified and minified).

https://github.com/TechnotronicOz/IECompat

(function() {
    var ie8Compat = function() {
        var agentStr = navigator.userAgent;
        if ( agentStr.indexOf('MSIE') === -1 ) return false;
        if ( agentStr.indexOf('Trident/4.0') > -1 ) {
            if ( agentStr.indexOf('MSIE 7.0') > -1 ) {
                return true;
            } else {
                return false;
            }
        } else {
            return false;
        }
    },

    ie9Compat = function() {
        var agentStr = navigator.userAgent;
        if ( agentStr.indexOf('MSIE') === -1 ) return false;
        if ( agentStr.indexOf('Trident/5.0') > -1 ) {
            if ( agentStr.indexOf('MSIE 7.0') > -1 ) {
                return true;
            } else {
                return false;
            }
        } else {
            return false;
        }
    };

    Modernizr.addTest('ie8compat', ie8Compat);
    Modernizr.addTest('ie9compat', ie9Compat);
}());


(function(){ie8Compat=function(){var a=navigator.userAgent;return-1===a.indexOf("MSIE")?!1:-1<a.indexOf("Trident/4.0")?-1<a.indexOf("MSIE 7.0")?!0:!1:!1};ie9Compat=function(){var a=navigator.userAgent;return-1===a.indexOf("MSIE")?!1:-1<a.indexOf("Trident/5.0")?-1<a.indexOf("MSIE 7.0")?!0:!1:!1};Modernizr.addTest("ie8compat",ie8Compat);Modernizr.addTest("ie9compat",ie9Compat)})();