且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何使用 JavaScript 检测 Internet Explorer (IE) 和 Microsoft Edge?

更新时间:2021-07-24 09:46:02

我不知道为什么,但我没有像其他人所说的那样在 userAgent 中看到Edge",所以我不得不另辟蹊径这可能会帮助一些人.

I don't know why, but I'm not seeing "Edge" in the userAgent like everyone else is talking about, so I had to take another route that may help some people.

我没有看 navigator.userAgent,而是看 navigator.appName 来区分是 IE<=10 还是 IE11 和 Edge.IE11 和 Edge 使用Netscape"的 appName,而其他所有迭代都使用Microsoft Internet Explorer".

Instead of looking at the navigator.userAgent, I looked at navigator.appName to distinguish if it was IE<=10 or IE11 and Edge. IE11 and Edge use the appName of "Netscape", while every other iteration uses "Microsoft Internet Explorer".

在我们确定浏览器是 IE11 或 Edge 后,我查看了 navigator.appVersion.我注意到在 IE11 中,字符串很长,里面有很多信息.我随意挑出了三叉戟"这个词,Edge 的 navigator.appVersion 里肯定没有这个词.测试这个词让我能够区分这两者.

After we determine that the browser is either IE11 or Edge, I then looked to navigator.appVersion. I noticed that in IE11 the string was rather long with a lot of information inside of it. I arbitrarily picked out the word "Trident", which is definitely not in the navigator.appVersion for Edge. Testing for this word allowed me to distinguish the two.

下面是一个函数,它将返回用户使用的 Internet Explorer 的数值.如果在 Microsoft Edge 上,则返回数字 12.

Below is a function that will return a numerical value of which Internet Explorer the user is on. If on Microsoft Edge it returns the number 12.

祝你好运,我希望这会有所帮助!

Good luck and I hope this helps!

function Check_Version(){
    var rv = -1; // Return value assumes failure.

    if (navigator.appName == 'Microsoft Internet Explorer'){

       var ua = navigator.userAgent,
           re  = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");

       if (re.exec(ua) !== null){
         rv = parseFloat( RegExp.$1 );
       }
    }
    else if(navigator.appName == "Netscape"){                       
       /// in IE 11 the navigator.appVersion says 'trident'
       /// in Edge the navigator.appVersion does not say trident
       if(navigator.appVersion.indexOf('Trident') === -1) rv = 12;
       else rv = 11;
    }       

    return rv;          
}