Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
432 views
in Technique[技术] by (71.8m points)

html - How can I detect Internet Explorer (IE) and Microsoft Edge using JavaScript?

I've looked around a lot, and I understand that there's a lot of ways to detect internet explorer.

My problem is this: I have an area on my HTML document, that when clicked, calls a JavaScript function that is incompatible with internet explorer of any kind. I want to detect if IE is being used, and if so, set the variable to true.

The problem is, I am writing my code out of Notepad++, and when I run the HTML code in browser, none of the methods for detecting IE work. I think the problem is that I am running it out of Notepad++. I need to be able to detect IE, so that based on the variable, I can disable that area of the site. I have tried this:

var isIE10 = false;

if (navigator.userAgent.indexOf("MSIE 10") > -1) {
    // this is internet explorer 10
    isIE10 = true;
   window.alert(isIE10);
}

var isIE = (navigator.userAgent.indexOf("MSIE") != -1);

if(isIE){
    if(!isIE10){
    window.location = 'pages/core/ie.htm';
    }
}

but it doesn't work. How can I detect IE out of Notepad++? That's what I'm testing the HTML out of, but I need a method that'll work with that.

edit

I noticed someone has marked this as a duplicate, and that is understandable. I suppose I was not clear. I cannot use a JQuery answer, so this is not a duplicate as I am asking for a vanilla JS answer.

Edit #2

Is there also a way to detect the Microsoft Edge browser?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Here is the latest correct way that I know of how to check for IE and Edge:

if (/MSIE 10/i.test(navigator.userAgent)) {
   // This is internet explorer 10
   window.alert('isIE10');
}

if (/MSIE 9/i.test(navigator.userAgent) || /rv:11.0/i.test(navigator.userAgent)) {
    // This is internet explorer 9 or 11
    window.location = 'pages/core/ie.htm';
}

if (/Edge/d./i.test(navigator.userAgent)){
   // This is Microsoft Edge
   window.alert('Microsoft Edge');
}

Note that you don't need the extra var isIE10 in your code because it does very specific checks now.

Also check out this page for the latest IE and Edge user agent strings because this answer may become outdated at some point: https://msdn.microsoft.com/en-us/library/hh869301%28v=vs.85%29.aspx


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...