How do I detect IE10 using javascript?

后端 未结 6 1945
离开以前
离开以前 2020-12-14 04:15

As many already posted in other questions (also in jQuery documentation), the old jQuery.browser.version is deprecated and works only in jquery1.3.

Do y

6条回答
  •  星月不相逢
    2020-12-14 04:55

    Internet Explorer has the feature of Conditional Compilation (http://www.javascriptkit.com/javatutors/conditionalcompile.shtml). You can use this:

    var isIE10 = false;
    /*@cc_on
        if (/^10/.test(@_jscript_version)) {
            isIE10 = true;
        }
    @*/
    alert(isIE10);
    

    DEMO: http://jsfiddle.net/X3Rvz/1/

    You can put this before all your JavaScript code, and from then on just reference isIE10.

    The conditional compilation won't run in non-IE, so isIE10 will still be false. And @_jscript_version will only start with 10 in IE 10.

    Conditional Comments aren't supported in IE 10, and the User-Agent string can be spoofed.

    Since minification usually removes comments, you can use eval or Function to find out in a similar fashion:

    var isIE10 = false;
    if (Function('/*@cc_on return /^10/.test(@_jscript_version) @*/')()) {
        isIE10 = true;
    }
    

    DEMO: http://jsfiddle.net/wauGa/2/


    UPDATE:

    To still avoid minification of comments but also combine detecting any version, you can use something like:

    var IE = (function () {
        "use strict";
    
        var ret, isTheBrowser,
            actualVersion,
            jscriptMap, jscriptVersion;
    
        isTheBrowser = false;
        jscriptMap = {
            "5.5": "5.5",
            "5.6": "6",
            "5.7": "7",
            "5.8": "8",
            "9": "9",
            "10": "10"
        };
        jscriptVersion = new Function("/*@cc_on return @_jscript_version; @*/")();
    
        if (jscriptVersion !== undefined) {
            isTheBrowser = true;
            actualVersion = jscriptMap[jscriptVersion];
        }
    
        ret = {
            isTheBrowser: isTheBrowser,
            actualVersion: actualVersion
        };
    
        return ret;
    }());
    

    And access the properties like IE.isTheBrowser and IE.actualVersion (which is translated from internal values of JScript versions).

提交回复
热议问题