How can I determine which version of IE a user is running in JavaScript?

后端 未结 12 1886
生来不讨喜
生来不讨喜 2021-02-04 04:48

In some existing code there is a test to see if the user is running IE, by checking if the object Browser.Engine.trident is defined and returns true.

But how can I deter

12条回答
  •  孤独总比滥情好
    2021-02-04 05:16

    As no-one seems to have said it yet:

    The test is needed inside a JavaScript function so a conditional comment doesn't seem suitable.

    You can easily put a conditional comment — a JScript conditional comment, not an HTML one — inside a function:

    function something() {
        var IE_WIN= false;
        var IE_WIN_7PLUS= false;
        /*@cc_on
        @if (@_win32)
            IE_WIN= true;
            @if (@_jscript_version>=5.7)
                IE_WIN_7PLUS = true;
            @end
        @end @*/
        ...
    }
    

    It's more typical to do the test once at global level though, and just check the stored flags thereafter.

    CCs are more reliable than sifting through the mess that the User-Agent string has become these days. String matching methods on navigator.userAgent can misidentify spoofing browsers such as Opera.

    Of course capability sniffing is much better for cross-browser code where it's possible, but for some cases — usually bug fix workarounds — you do need to identify IE specifically, and CCs are probably the best way to do that today.

提交回复
热议问题