如何检测IE和Edge浏览器?

27

在IE或Microsoft Edge中无法正确使用视差效果。我在论坛上查找并未找到解决方案。我想现在提出一个解决方案,希望有效。如果用户使用IE或Edge浏览器,我想显示一条消息。不确定如何检测正在使用的浏览器是哪一个。

这里是我正在尝试使用的一些JavaScript代码:

<script src="https://github.com/ded/bowser/blob/master/src/bowser.js"></script>

    // Determine Browser Used
browser = require('bowser').browser; becomes browser = require('bowser');
if (bowser.msie || bowser.msedge) {
  alert('Hello Microsoft User');
}
任何帮助将不胜感激,或者如果有更好的解决方案也请告知。 http://peaceandplentyinn.mybnbwebsite.com

5
忘掉这个信息,人们不想被告知要使用不同的浏览器来访问您的网站。人们想要内容。只要能够访问内容,他们就不会介意任何视差缺失。Edge似乎存在固定背景的问题,在滚动时导致它们上下跳动。然而,我认为这是一个与浏览器相关的问题,而不是您的代码问题。 - ROAL
更可靠的方法是进行特性检测而不是浏览器嗅探。 - Rob
我该如何进行这个特性检测? - Brent Nicolet
6
现在似乎推荐使用特性检测,但这个概念存在缺陷。问题在于,有时虽然实现了某个特性,但仍可能存在错误,导致您无法按预期使用它。因此,您需要检测具有特定错误的浏览器,以使页面在该浏览器上能够正常工作。或者,是否有更好的方法来解决浏览器错误? - Russell Horwood
3个回答

75

我怀疑你是否真正需要检测浏览器。但是,以下是一种方法(不一定需要使用库):

// detect IE8 and above, and edge
if (document.documentMode || /Edge/.test(navigator.userAgent)) {
    alert('Hello Microsoft User!');
}

2
这不适用于IE8+。它只适用于Edge。 - Trolzie
在 MS Edge 中,XMLHTTPRequest 对象不会触发进度事件,并且没有很好的方法来进行特性检测,因此这是使用它的一个原因(现在已经修复,我必须进行版本检测 xD)- https://developer.microsoft.com/en-us/microsoft-edge/platform/issues/12224510/ - Wayne Bloss

2

对我来说更好的是这样:

var uA = window.navigator.userAgent,
    isIE = /msie\s|trident\/|edge\//i.test(uA) && !!(document.uniqueID || document.documentMode || window.ActiveXObject || window.MSInputMethodContext),
    checkVersion = (isIE && +(/(edge\/|rv:|msie\s)([\d.]+)/i.exec(uA)[2])) || NaN;

Go run: http://jsfiddle.net/Webnewbie/apa1nvu8/


这个在 Microsoft Edge 42.17134.1.0 上已经不再起作用了。 - tmm1

1
我使用这些函数,即使用户代理设置为其他值也能正常工作。
if (document.documentMode) 
{
    console.log('Hello Microsoft IE User!');
}

if (!document.documentMode && window.msWriteProfilerMark) {
    console.log('Hello Microsoft Edge User!');
}

if (window.msWriteProfilerMark) 
{
    console.log('Hello Microsoft User!');
}

这段文本检测Chredge/Edgium(又名Anaheim)。
function isEdg()
{ 

    for (var i = 0, u="Microsoft", l =u.length; i < navigator.plugins.length; i++)
    {
        if (navigator.plugins[i].name != null && navigator.plugins[i].name.substr(0, l) === u)
            return true;
    }

    return false;
}

这个可以检测到 Chromium 浏览器:

function isChromium()
{ 

    for (var i = 0, u="Chromium", l =u.length; i < navigator.plugins.length; i++)
    {
        if (navigator.plugins[i].name != null && navigator.plugins[i].name.substr(0, l) === u)
            return true;
    }

    return false;
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接