如何检测Safari,Chrome,IE,Firefox和Opera浏览器?

Fra*_*nkC 738 javascript browser-detection

我有FF,Chrome,IE,Opera和Safari的5个插件/扩展.

如何识别用户浏览器并重定向(单击安装按钮后)以下载相应的插件?

Rob*_*b W 1560

用于浏览器可靠检测的Google搜索通常会导致检查用户代理字符串.这种方法可靠,因为欺骗这个值是微不足道的.
我编写了一种通过duck-typing来检测浏览器的方法.

如果确实有必要,请仅使用浏览器检测方法,例如显示特定于浏览器的指令以安装扩展程序.尽可能使用特征检测.

演示:https://jsfiddle.net/311aLtkz/

// Opera 8.0+
var isOpera = (!!window.opr && !!opr.addons) || !!window.opera || navigator.userAgent.indexOf(' OPR/') >= 0;

// Firefox 1.0+
var isFirefox = typeof InstallTrigger !== 'undefined';

// Safari 3.0+ "[object HTMLElementConstructor]" 
var isSafari = /constructor/i.test(window.HTMLElement) || (function (p) { return p.toString() === "[object SafariRemoteNotification]"; })(!window['safari'] || (typeof safari !== 'undefined' && safari.pushNotification));

// Internet Explorer 6-11
var isIE = /*@cc_on!@*/false || !!document.documentMode;

// Edge 20+
var isEdge = !isIE && !!window.StyleMedia;

// Chrome 1 - 71
var isChrome = !!window.chrome && (!!window.chrome.webstore || !!window.chrome.runtime);

// Blink engine detection
var isBlink = (isChrome || isOpera) && !!window.CSS;


var output = 'Detecting browsers by ducktyping:<hr>';
output += 'isFirefox: ' + isFirefox + '<br>';
output += 'isChrome: ' + isChrome + '<br>';
output += 'isSafari: ' + isSafari + '<br>';
output += 'isOpera: ' + isOpera + '<br>';
output += 'isIE: ' + isIE + '<br>';
output += 'isEdge: ' + isEdge + '<br>';
output += 'isBlink: ' + isBlink + '<br>';
document.body.innerHTML = output;
Run Code Online (Sandbox Code Playgroud)

可靠性分析

先前的方法依赖于渲染引擎(的性质-moz-box-sizing-webkit-transform)来检测浏览器.这些前缀最终将被删除,因此为了使检测更加健壮,我切换到特定于浏览器的特性:

  • Internet Explorer:JScript的条件编译(直到IE9)和document.documentMode.
  • Edge:在Trident和Edge浏览器中,Microsoft的实现公开了StyleMedia构造函数.不包括Trident让我们离开Edge.
  • Firefox:Firefox用于安装附加组件的API: InstallTrigger
  • Chrome:全局chrome对象,包含多个属性,包括已记录的chrome.webstore对象.
    • chrome.webstore在最新版本中,不推荐使用Update 3 并且未定义更新
  • Safari:构造函数命名中的唯一命名模式.这是所有列出的属性中最不耐用的方法,猜猜是什么?在Safari 9.1.3中,它已得到修复.所以我们正在检查SafariRemoteNotification,这是在7.1版之后引入的,以涵盖3.0及以上版本的所有Safaris.
  • Opera:window.opera已存在多年,但当Opera用Blink + V8(Chromium使用)取代其引擎时,它将被删除.
    • 更新1:Opera 15已经发布,其UA字符串看起来像Chrome,但增加了"OPR".在此版本中,chrome定义了对象(但chrome.webstore不是).由于Opera努力克隆Chrome,我使用用户代理嗅探来实现此目的.
    • 更新2:!!window.opr && opr.addons可用于检测Opera 20+(常青树).
  • Blink:一旦谷歌开启了Chrome 28,就会CSS.supports() 在Blink中推出.当然,与Opera中使用的Blink相同.

成功通过以下测试:

  • Firefox 0.8 - 61
  • Chrome 1.0 - 71
  • Opera 8.0 - 34
  • Safari 3.0 - 10
  • IE 6 - 11
  • 边缘 - 20-42

2016年11月更新,包括检测9.1.3及更高版本的Safari浏览器

在2018年8月更新,以更新有关chrome,firefox IE和edge的最新成功测试.

在2019年1月更新以修复Chrome检测(因为window.chrome.webstore折旧)并包含最新的成功测试.

  • `isSafari`不适用于Safari 10.我会争辩说这是一个糟糕的解决方案(不是我有一个好的解决方案).我们无法保证您检查的许多内容不会被删除或其他浏览器不会添加.每个使用此代码检查Safari的网站都破解了macOS Sierra或Safari 10升级:( (55认同)
  • window.chrome.webstore从Chrome ver开始不推荐使用.71:https://blog.chromium.org/2018/06/improving-extension-transparency-for.html (21认同)
  • 但是,这些浏览器的**移动版**以及**桌面版**也经过了测试吗?说实话,每个平台有不同的移动版本和不同的桌面版本.实际上,firefox有3个二进制文件用于Windows,Linux,Mac OS和2个用于Android和iOS的二进制文件. (9认同)
  • 仅供参考这不适用于Chrome扩展程序,因为```window.chrome.webstore```在那里未定义.尚未使用Firefox Extensions进行检查.其他地方提到的```is.js```在Chrome和Firefox Extensions中都有效. (5认同)
  • 在我看来,我们必须经历这一切才能找出正在使用的浏览器,这似乎很荒谬。我认为浏览器供应商同意一个他们都可以发送的标准 JavaScript 变量是有意义的,一些疯狂的名字,比如“browserName”! (4认同)
  • 它不再起作用了 (4认同)
  • 当前的`isSafari`在Safari 10.1.2下的`<iframe>`下不起作用 (3认同)
  • 我在safari中遇到这个错误`'safari'没有定义` (3认同)
  • Chrome测试(由于v71过时)可以通过`!! window.chrome &&!isOpera`修复. (3认同)
  • “因为欺骗这个值是微不足道的。” 所以呢?如果浏览器冒充其他东西,那么网站为什么要关心呢? (3认同)
  • 从 macOS 10.15.6 Catalina 上的 Safari 14 Beta 2 开始,Safari 检测不再起作用。 (3认同)
  • 阅读完所有评论后,我将永远不会再使用鸭子打字来检测正在使用哪个浏览器。使用 userAgent 字符串并非没有问题,但似乎仍然是最佳选择,并且仍然是 Google 的首选方法。 (3认同)
  • 到 2022 年,使用 InstallTrigger 进行的 Firefox 检测将会中断,因为它会在 Firefox 103 左右消失。 (3认同)
  • @gman我同意你的看法.当您部署它时,此解决方案可以正常工作,但随着浏览器的发展,它不会真正面向未来. (2认同)
  • 在Chrome中,它对Blink也说"真实". (2认同)
  • 注意:当 Chrome 无头运行时,没有 `window.chrome` 对象。 (2认同)
  • "欺骗这个价值是微不足道的" - 为什么这个被承认呢?任何形式的浏览器检测*都可以被欺骗.这根本不重要; 浏览器检测在很大程度上是一种方便的方式,让人们知道浏览器UI提示,已知问题等,而用户代理是完全有效的方法.这个答案对于特征检测与用户代理嗅探有着混乱的误解,我真的不确定它为何如此受欢迎.你所说的没有什么在技术上是不正确的,但这是一个令人难以置信的无益答案. (2认同)
  • FYI` !! window.chrome && !! window.chrome.webstore;`当Chrome处于无头模式时`返回`false`. (2认同)
  • 原来`!! window.chrome &amp;&amp;!isOpera`不起作用,因为它与Edge相匹配。 (2认同)
  • 花了一些时间来弄清楚,所以可能会有所帮助:当您打开本地域或IP时,`!window.chrome &amp;&amp;(!! window.chrome.webstore || !! window.chrome.runtime)`将会失败!当您浏览到本地页面时,Chrome似乎会使运行时失效。 (2认同)
  • 添加到@eyecatchUp,似乎chrome测试可以在https页上运行,但不能在http页上运行(没有ssl)。 (2认同)
  • 这似乎更好地工作:`var isChrome = !! window.chrome &amp;&amp;(!! window.chrome.webstore || !! window.chrome.csi)`至少当URL不是SSL且在Edge上正确报告时,它才有效。我不确定Safari。 (2认同)
  • Chrome 80 和 81 不会被检测到。而 iOS 上的 Safari 则不然(不知道它的版本标签在哪里)。 (2认同)
  • 我正在运行 Edge Chromium,但它显示错误。一切都是假的。 (2认同)
  • 不幸的是,在 iOS 12.4.9 ipad Air 下,所有三种浏览器都无法工作:Safari、Chrome、Firefox (2认同)
  • @dmikester1——供应商不想标准化 *navigator.useragent* 的一个原因是他们不希望用户看到“*您的浏览器不受支持,请从…下载支持的浏览器*”,就像 Netscape 与 IE 时代一样。 (2认同)
  • Chrome 71+ 返回 false。这个答案需要更新... (2认同)
  • 这对我不起作用。我在 MS Edge 版本 108.0.1462.46 中得到的都是“假”。您的答案被严重高估了,有 1900 多个赞成票。@Nimesh 下面的答案只有 184 票,但它有效! (2认同)
  • 对于 Firefox 112+ 版本,“InstallTrigger”检查不再起作用。`typeof mozInnerScreenX !== 'undefined'` 可能是一个替代方案。 (2认同)

Nim*_*esh 121

您可以尝试以下方式检查浏览器版本.

    <!DOCTYPE html>
    <html>
    <body>
    <p>What is the name(s) of your browser?</p>
    <button onclick="myFunction()">Try it</button>
    <p id="demo"></p>
    <script>

    function myFunction() { 
     if((navigator.userAgent.indexOf("Opera") || navigator.userAgent.indexOf('OPR')) != -1 ) 
    {
        alert('Opera');
    }
    else if(navigator.userAgent.indexOf("Chrome") != -1 )
    {
        alert('Chrome');
    }
    else if(navigator.userAgent.indexOf("Safari") != -1)
    {
        alert('Safari');
    }
    else if(navigator.userAgent.indexOf("Firefox") != -1 ) 
    {
         alert('Firefox');
    }
    else if((navigator.userAgent.indexOf("MSIE") != -1 ) || (!!document.documentMode == true )) //IF IE > 10
    {
      alert('IE'); 
    }  
    else 
    {
       alert('unknown');
    }
    }
    </script>

    </body>
    </html>
Run Code Online (Sandbox Code Playgroud)

如果您只需要知道IE浏览器版本,那么您可以按照以下代码.此代码适用于IE6到IE11的版本

<!DOCTYPE html>
<html>
<body>

<p>Click on Try button to check IE Browser version.</p>

<button onclick="getInternetExplorerVersion()">Try it</button>

<p id="demo"></p>

<script>
function getInternetExplorerVersion() {
   var ua = window.navigator.userAgent;
        var msie = ua.indexOf("MSIE ");
        var rv = -1;

        if (msie > 0 || !!navigator.userAgent.match(/Trident.*rv\:11\./))      // If Internet Explorer, return version number
        {               

            if (isNaN(parseInt(ua.substring(msie + 5, ua.indexOf(".", msie))))) {
                //For IE 11 >
                if (navigator.appName == 'Netscape') {
                    var ua = navigator.userAgent;
                    var re = new RegExp("Trident/.*rv:([0-9]{1,}[\.0-9]{0,})");
                    if (re.exec(ua) != null) {
                        rv = parseFloat(RegExp.$1);
                        alert(rv);
                    }
                }
                else {
                    alert('otherbrowser');
                }
            }
            else {
                //For < IE11
                alert(parseInt(ua.substring(msie + 5, ua.indexOf(".", msie))));
            }
            return false;
        }}
</script>

</body>
</html>
Run Code Online (Sandbox Code Playgroud)

  • Stackoverflow使用此方法 (11认同)
  • 怎么样微软边缘? (5认同)
  • 为什么会写这么多行代码?userAgent不明确. (3认同)
  • 在检查safari之前,上面的答案检查了chrome.因为safari在useragent中没有`chrome`关键字.safari useragent的例子 - "mozilla/5.0(macintosh; intel mac os x 10_11_5)applewebkit/601.6.17(khtml,like gecko)version/9.1.1 safari/601.6.17` (3认同)
  • 在Opera(最新版本)中进行测试时,这会为我返回"Chrome".为了解决这个问题,我将Opera if语句改为:if(navigator.userAgent.indexOf("Opera")!= -1 || navigator.userAgent.indexOf('OPR')!= -1)` (3认同)
  • 出于某种原因,我的Chrome浏览器中的“ navigator.userAgent”包含Safari:“ Mozilla / 5.0(X11; Linux x86_64)AppleWebKit / 537.36(KHTML,例如Gecko)Chrome / 56.0.2924.87 Safari / 537.36”,但是我的firefox没有: ““ Mozilla / 5.0(X11; Ubuntu; Linux x86_64; rv:25.0)Gecko / 20100101 Firefox / 25.0”” (2认同)
  • 这是预期和期望的:如果有人将其 UA 设置为不同的浏览器,他们这样做是为了获取为该浏览器提供的内容。用户代理欺骗实际上就是为什么您需要基于 userAgent 的浏览器检测解决方案而不是使用鸭子类型,因为您为不同的浏览器生成不同的内容(而不是尝试基于 JS 支持实现渐进式增强,后者应该使用鸭子类型因为你需要特征检测)。 (2认同)

Raf*_*yng 59

我知道使用lib可能有点过分,但只是为了丰富线程,你可以检查is.js这样做的方式:

is.firefox();
is.ie(6);
is.not.safari();
Run Code Online (Sandbox Code Playgroud)

  • 值得注意的是,它主要是在进行用户代理检测.在某些地方补充了供应商检测/某些功能检测. (8认同)
  • jQuery曾经包含类似的属性:$ .browser.msie ...已从1.9版本中删除http://api.jquery.com/jquery.browser/ (3认同)

wil*_*ire 43

如果有人发现这个有用,我已经将Rob W的答案变成了一个返回浏览器字符串而不是浮动多个变量的函数.由于浏览器在没有重新加载的情况下也无法真正改变,我已经使其缓存结果以防止它在下次调用函数时需要将其解决.

/**
 * Gets the browser name or returns an empty string if unknown. 
 * This function also caches the result to provide for any 
 * future calls this function has.
 *
 * @returns {string}
 */
var browser = function() {
    // Return cached result if avalible, else get result then cache it.
    if (browser.prototype._cachedResult)
        return browser.prototype._cachedResult;

    // Opera 8.0+
    var isOpera = (!!window.opr && !!opr.addons) || !!window.opera || navigator.userAgent.indexOf(' OPR/') >= 0;

    // Firefox 1.0+
    var isFirefox = typeof InstallTrigger !== 'undefined';

    // Safari 3.0+ "[object HTMLElementConstructor]" 
    var isSafari = /constructor/i.test(window.HTMLElement) || (function (p) { return p.toString() === "[object SafariRemoteNotification]"; })(!window['safari'] || safari.pushNotification);

    // Internet Explorer 6-11
    var isIE = /*@cc_on!@*/false || !!document.documentMode;

    // Edge 20+
    var isEdge = !isIE && !!window.StyleMedia;

    // Chrome 1+
    var isChrome = !!window.chrome && !!window.chrome.webstore;

    // Blink engine detection
    var isBlink = (isChrome || isOpera) && !!window.CSS;

    return browser.prototype._cachedResult =
        isOpera ? 'Opera' :
        isFirefox ? 'Firefox' :
        isSafari ? 'Safari' :
        isChrome ? 'Chrome' :
        isIE ? 'IE' :
        isEdge ? 'Edge' :
        isBlink ? 'Blink' :
        "Don't know";
};

console.log(browser());
Run Code Online (Sandbox Code Playgroud)

  • 属性 `window.chrome.webstore` 在 Chrome 71 中被删除,因此这种方法不再有效。 (6认同)
  • 我喜欢这个,但我更倾向于回退到userAgent(),而不是"不知道". (4认同)
  • 在Edge浏览器中,它返回* Chrome * (2认同)
  • @eFriend我更新了最新浏览器测试的答案. (2认同)
  • 我在 Safari、Firfox 和 Chrome 中尝试过此操作,总是返回“不知道”。 (2认同)

Kyl*_*Mit 36

以下是几个处理浏览器检测的着名库,截至2019年2月.

Bowser by lancedikson - 3,216★s - 最后更新时间:2019年2月9日 - 2.9KB

var result = bowser.getParser(window.navigator.userAgent);
console.log(result);
document.write("You are using " + result.parsedResult.browser.name +
               " v" + result.parsedResult.browser.version + 
               " on " + result.parsedResult.os.name);
Run Code Online (Sandbox Code Playgroud)
<script src="https://unpkg.com/bowser@2.4.0/es5.js"></script>
Run Code Online (Sandbox Code Playgroud)

Platform.js by bestiejs - 2,250★s - 最后更新时间:2018年10月30日 - 5.9KB

console.log(platform);
document.write("You are using " + platform.name +
               " v" + platform.version + 
               " on " + platform.os);
Run Code Online (Sandbox Code Playgroud)
<script src="https://cdnjs.cloudflare.com/ajax/libs/platform/1.3.5/platform.min.js"></script>
Run Code Online (Sandbox Code Playgroud)

gabceb的jQuery浏览器 - 504★s - 最后更新时间2015年11月23日 - 1.3KB

console.log($.browser)
document.write("You are using " + $.browser.name +
               " v" + $.browser.versionNumber + 
               " on " + $.browser.platform);
Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-browser/0.1.0/jquery.browser.min.js"></script>
Run Code Online (Sandbox Code Playgroud)

由darcyclarke检测的Detect.js(存档) - 522★s - 最后更新时间2015年10月26日 - 2.9KB

var result = detect.parse(navigator.userAgent);
console.log(result);
document.write("You are using " + result.browser.family +
               " v" + result.browser.version + 
               " on " + result.os.family);
Run Code Online (Sandbox Code Playgroud)
<script src="https://cdnjs.cloudflare.com/ajax/libs/Detect.js/2.2.2/detect.min.js"></script>
Run Code Online (Sandbox Code Playgroud)

由QuirksMode进行的浏览器检测(存档) - 最后更新时间为2013年11月14日 - 884B

console.log(BrowserDetect)
document.write("You are using " + BrowserDetect.browser +
               " v" + BrowserDetect.version + 
               " on " + BrowserDetect.OS);
Run Code Online (Sandbox Code Playgroud)
<script src="https://kylemit.github.io/libraries/libraries/BrowserDetect.js"></script>
Run Code Online (Sandbox Code Playgroud)


值得注意的提及:

  • WhichBrowser - 1,355★s - 最后更新时间为2018年10月2日
  • Modernizr - 23,397★s - 最后更新2019年1月12日 - 为了喂养一匹美联储的马,功能检测应该驱动任何canIuse风格的问题.浏览器检测实际上只是为各个浏览器提供自定义图像,下载文件或说明.

进一步阅读

  • 为了不重新发明轮子,花费几 Kb 的开销是值得的。 (5认同)

Ale*_*lin 14

简短的变种

var browser = (function(){
  var test = function(regexp) { return regexp.test(window.navigator.userAgent);}
  switch(true){
	case test(/edge/i): return "edge";
	case test(/opr/i) && (!!window.opr || !!window.opera): return "opera";
	case test(/chrome/i) && !!window.chrome: return "chrome";
	case test(/trident/i) : return "ie";
	case test(/firefox/i) : return "firefox";
	case test(/safari/i): return "safari";
	default: return "other";
  }
})();
console.log(browser)
Run Code Online (Sandbox Code Playgroud)

  • 这将在 ios 上使用“chrome”浏览时显示“safari” (3认同)
  • 此方法适用于桌面版 Chrome 和 Firefox 以及 iOS 版 Safari。iOS 上的 Chrome 和 Firefox 会失败。 (2认同)

pil*_*lau 11

这是Rob的答案的2016年调整版,包括Microsoft Edge和Blink的检测:

(编辑:我用上述信息更新了Rob的答案.)

// Opera 8.0+ (UA detection to detect Blink/v8-powered Opera)
isOpera = !!window.opera || navigator.userAgent.indexOf(' OPR/') >= 0;
// Firefox 1.0+
isFirefox = typeof InstallTrigger !== 'undefined';
// Safari 3.0+
isSafari = /constructor/i.test(window.HTMLElement) || (function (p) { return p.toString() === "[object SafariRemoteNotification]"; })(!window['safari'] || safari.pushNotification);
// Internet Explorer 6-11
isIE = /*@cc_on!@*/false || !!document.documentMode;
// Edge 20+
isEdge = !isIE && !!window.StyleMedia;
// Chrome 1+
isChrome = !!window.chrome && !!window.chrome.webstore;
// Blink engine detection
isBlink = (isChrome || isOpera) && !!window.CSS;

/* Results: */
console.log("isOpera", isOpera);
console.log("isFirefox", isFirefox);
console.log("isSafari", isSafari);
console.log("isIE", isIE);
console.log("isEdge", isEdge);
console.log("isChrome", isChrome);
console.log("isBlink", isBlink);
Run Code Online (Sandbox Code Playgroud)

这种方法的优点在于它依赖于浏览器引擎属性,因此它甚至涵盖了衍生浏览器,例如Yandex或Vivaldi,它们实际上与他们使用的引擎的主要浏览器兼容.唯一的例外是Opera,它依赖于用户代理嗅探,但今天(即版本15及以上)甚至Opera本身只是Blink的一个shell.


dnn*_*nns 8

谢谢大家.我在最近的浏览器上测试了代码片段:Chrome 55,Firefox 50,IE 11和Edge 38,我想出了以下组合,这些组合对我来说都适用.我确信它可以改进,但它是一个快速的解决方案,无论谁需要:

var browser_name = '';
isIE = /*@cc_on!@*/false || !!document.documentMode;
isEdge = !isIE && !!window.StyleMedia;
if(navigator.userAgent.indexOf("Chrome") != -1 && !isEdge)
{
    browser_name = 'chrome';
}
else if(navigator.userAgent.indexOf("Safari") != -1 && !isEdge)
{
    browser_name = 'safari';
}
else if(navigator.userAgent.indexOf("Firefox") != -1 ) 
{
    browser_name = 'firefox';
}
else if((navigator.userAgent.indexOf("MSIE") != -1 ) || (!!document.documentMode == true )) //IF IE > 10
{
    browser_name = 'ie';
}
else if(isEdge)
{
    browser_name = 'edge';
}
else 
{
   browser_name = 'other-browser';
}
$('html').addClass(browser_name);
Run Code Online (Sandbox Code Playgroud)

它为HTML添加了一个CSS类,其中包含浏览器的名称.


Ton*_*ith 8

不知道它是否对任何人有用,但是这里有一个使TypeScript满意的变体。

export function getBrowser() {

// Opera 8.0+
if ((!!window["opr"] && !!["opr"]["addons"]) || !!window["opera"] || navigator.userAgent.indexOf(' OPR/') >= 0) {
    return 'opera';
}

// Firefox 1.0+
if (typeof window["InstallTrigger"] !== 'undefined') {
    return 'firefox';
}

// Safari 3.0+ "[object HTMLElementConstructor]" 
if (/constructor/i.test(window["HTMLElement"]) || (function(p) { return p.toString() === "[object SafariRemoteNotification]"; })(!window['safari'] || (typeof window["safari"] !== 'undefined' && window["safari"].pushNotification))) {
    return 'safari';
}

// Internet Explorer 6-11
if (/*@cc_on!@*/false || !!document["documentMode"]) {
    return 'ie';
}

// Edge 20+
if (!(/*@cc_on!@*/false || !!document["documentMode"]) && !!window["StyleMedia"]) {
    return 'edge';
}

// Chrome 1+
if (!!window["chrome"] && !!window["chrome"].webstore) {
    return 'chrome';
}

// Blink engine detection
if (((!!window["chrome"] && !!window["chrome"].webstore) || ((!!window["opr"] && !!["opr"]["addons"]) || !!window["opera"] || navigator.userAgent.indexOf(' OPR/') >= 0)) && !!window["CSS"]) {
    return 'blink';
}
Run Code Online (Sandbox Code Playgroud)

}


Mas*_*nes 7

您可以使用trycatch使用不同的浏览器错误消息.IE和边缘混在一起,但我使用了Rob W的鸭子打字(基于这个项目:https://www.khanacademy.org/computer-programming/i-have-opera/2395080328).

var getBrowser = function() {        
    try {
        var e;
        var f = e.width;
    } catch(e) {
        var err = e.toString();

        if(err.indexOf("not an object") !== -1) {
            return "safari";
        } else if(err.indexOf("Cannot read") !== -1) {
            return "chrome";
        } else if(err.indexOf("e is undefined") !== -1) {
            return "firefox";
        } else if(err.indexOf("Unable to get property 'width' of undefined or null reference") !== -1) {
            if(!(false || !!document.documentMode) && !!window.StyleMedia) {
                return "edge";
            } else {
                return "IE";
            }
        } else if(err.indexOf("cannot convert e into object") !== -1) {
            return "opera";
        } else {
            return undefined;
        }
    }
};
Run Code Online (Sandbox Code Playgroud)


Luz*_*ral 7

UAParser是 JavaScript 库之一,用于从 userAgent 字符串中识别浏览器、引擎、操作系统、CPU 和设备类型/型号。

有可用的 CDN。在这里,我提供了一个使用 UAParser 检测浏览器的示例代码。

<!doctype html>
<html>
<head>
<script src="https://cdn.jsdelivr.net/npm/ua-parser-js@0/dist/ua-parser.min.js"></script>
<script type="text/javascript">
    var parser = new UAParser();
    var result = parser.getResult();
    console.log(result.browser);     // {name: "Chromium", version: "15.0.874.106"}
</script>
</head>
<body>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)

现在您可以使用 的值result.browser来有条件地对您的页面进行编程。

源码教程:如何使用JavaScript检测浏览器、引擎、操作系统、CPU和设备?

  • 一千行代码你称之为轻量级? (5认同)

Irs*_*han 7

检测桌面和移动浏览器:Edge、Opera、Chrome、Safari、Firefox、IE

我对 @nimesh 代码做了一些更改,现在它也适用于 Edge,并且修复了 Opera 问题:

function getBrowserName() {

    if ( navigator.userAgent.indexOf("Edge") > -1 && navigator.appVersion.indexOf('Edge') > -1 ) {
        return 'Edge';
    }
    else if( navigator.userAgent.indexOf("Opera") != -1 || navigator.userAgent.indexOf('OPR') != -1 )
    {
        return 'Opera';
    }
    else if( navigator.userAgent.indexOf("Chrome") != -1 )
    {
        return 'Chrome';
    }
    else if( navigator.userAgent.indexOf("Safari") != -1)
    {
        return 'Safari';
    }
    else if( navigator.userAgent.indexOf("Firefox") != -1 ) 
    {
        return 'Firefox';
    }
    else if( ( navigator.userAgent.indexOf("MSIE") != -1 ) || (!!document.documentMode == true ) ) //IF IE > 10
    {
        return 'IE';
    }  
    else 
    {
        return 'unknown';
    }
}
Run Code Online (Sandbox Code Playgroud)

谢谢@nimesh 用户:2063564


Val*_*ash 6

如果您需要知道某个特定浏览器的数字版本是什么,您可以使用以下代码段。目前它会告诉你 Chrome/Chromium/Firefox 的版本:

var match = $window.navigator.userAgent.match(/(?:Chrom(?:e|ium)|Firefox)\/([0-9]+)\./);
var ver = match ? parseInt(match[1], 10) : 0;
Run Code Online (Sandbox Code Playgroud)


Ank*_*kit 6

检测浏览器及其版本

此代码片段基于MDN的文章。他们给出了有关可用于检测浏览器名称的各种关键字的简短提示。

参考

上图中显示的数据不足以检测所有浏览器,例如Firefox 的 userAgent 将使用 Fxios 作为关键字,而不是 Firefox。

还进行了一些更改以检测EdgeUCBrowser等浏览器

目前,通过在开发工具的帮助下更改 userAgent(如何更改 userAgent),代码已针对以下浏览器进行了测试:

  • 火狐
  • 铬合金
  • IE
  • 边缘
  • 歌剧
  • 苹果浏览器
  • UC浏览器

getBrowser = () => {
    const userAgent = navigator.userAgent;
    let browser = "unkown";
    // Detect browser name
    browser = (/ucbrowser/i).test(userAgent) ? 'UCBrowser' : browser;
    browser = (/edg/i).test(userAgent) ? 'Edge' : browser;
    browser = (/googlebot/i).test(userAgent) ? 'GoogleBot' : browser;
    browser = (/chromium/i).test(userAgent) ? 'Chromium' : browser;
    browser = (/firefox|fxios/i).test(userAgent) && !(/seamonkey/i).test(userAgent) ? 'Firefox' : browser;
    browser = (/; msie|trident/i).test(userAgent) && !(/ucbrowser/i).test(userAgent) ? 'IE' : browser;
    browser = (/chrome|crios/i).test(userAgent) && !(/opr|opera|chromium|edg|ucbrowser|googlebot/i).test(userAgent) ? 'Chrome' : browser;;
    browser = (/safari/i).test(userAgent) && !(/chromium|edg|ucbrowser|chrome|crios|opr|opera|fxios|firefox/i).test(userAgent) ? 'Safari' : browser;
    browser = (/opr|opera/i).test(userAgent) ? 'Opera' : browser;

    // detect browser version
    switch (browser) {
        case 'UCBrowser': return `${browser}/${browserVersion(userAgent,/(ucbrowser)\/([\d\.]+)/i)}`;
        case 'Edge': return `${browser}/${browserVersion(userAgent,/(edge|edga|edgios|edg)\/([\d\.]+)/i)}`;
        case 'GoogleBot': return `${browser}/${browserVersion(userAgent,/(googlebot)\/([\d\.]+)/i)}`;
        case 'Chromium': return `${browser}/${browserVersion(userAgent,/(chromium)\/([\d\.]+)/i)}`;
        case 'Firefox': return `${browser}/${browserVersion(userAgent,/(firefox|fxios)\/([\d\.]+)/i)}`;
        case 'Chrome': return `${browser}/${browserVersion(userAgent,/(chrome|crios)\/([\d\.]+)/i)}`;
        case 'Safari': return `${browser}/${browserVersion(userAgent,/(safari)\/([\d\.]+)/i)}`;
        case 'Opera': return `${browser}/${browserVersion(userAgent,/(opera|opr)\/([\d\.]+)/i)}`;
        case 'IE': const version = browserVersion(userAgent,/(trident)\/([\d\.]+)/i);
            // IE version is mapped using trident version 
            // IE/8.0 = Trident/4.0, IE/9.0 = Trident/5.0
            return version ? `${browser}/${parseFloat(version) + 4.0}` : `${browser}/7.0`;
        default: return `unknown/0.0.0.0`;
    }
}

browserVersion = (userAgent,regex) => {
    return userAgent.match(regex) ? userAgent.match(regex)[2] : null;
}

console.log(getBrowser());
Run Code Online (Sandbox Code Playgroud)


小智 5

还有一种不那么“hacky”的方法适用于所有流行的浏览器。Google 在他们的Closure Library 中包含了浏览器检查。特别是,看看goog.userAgentgoog.userAgent.product。通过这种方式,如果浏览器呈现的方式发生变化,您也可以及时了解最新信息(假设您始终运行最新版本的闭包编译器。)


Mal*_*med 5

您可以使用 Detect-browser.js,JavaScript 库,检测并打印浏览器信息对象,包括浏览器语言/名称、用户代理、设备类型、用户操作系统、引荐来源网址、在线/0离线、用户时区、屏幕分辨率和启用的 cookie 。

从这里获取detector-browser.js

它会给你类似的东西:

在此输入图像描述


Hen*_*ren 5

这是我的定制解决方案。

        const inBrowser = typeof window !== 'undefined'
        const UA = inBrowser && window.navigator.userAgent.toLowerCase()
        const isIE =
          UA && /; msie|trident/i.test(UA) && !/ucbrowser/i.test(UA).test(UA)
        const isEdge = UA && /edg/i.test(UA)
        const isAndroid = UA && UA.indexOf('android') > 0
        const isIOS = UA && /iphone|ipad|ipod|ios/i.test(UA)
        const isChrome =
          UA &&
          /chrome|crios/i.test(UA) &&
          !/opr|opera|chromium|edg|ucbrowser|googlebot/i.test(UA)
        const isGoogleBot = UA && /googlebot/i.test(UA)
        const isChromium = UA && /chromium/i.test(UA)
        const isUcBrowser = UA && /ucbrowser/i.test(UA)
        const isSafari =
          UA &&
          /safari/i.test(UA) &&
          !/chromium|edg|ucbrowser|chrome|crios|opr|opera|fxios|firefox/i.test(UA)
        const isFirefox = UA && /firefox|fxios/i.test(UA) && !/seamonkey/i.test(UA)
        const isOpera = UA && /opr|opera/i.test(UA)
        const isMobile =
          /\b(BlackBerry|webOS|iPhone|IEMobile)\b/i.test(UA) ||
          /\b(Android|Windows Phone|iPad|iPod)\b/i.test(UA)
        const isSamsung = UA && /samsungbrowser/i.test(UA)
        const isIPad = UA && /ipad/.test(UA)
        const isIPhone = UA && /iphone/.test(UA)
        const isIPod = UA && /ipod/.test(UA)
    
        console.log({
          UA,
          isAndroid,
          isChrome,
          isChromium,
          isEdge,
          isFirefox,
          isGoogleBot,
          isIE,
          isMobile,
          isIOS,
          isIPad,
          isIPhone,
          isIPod,
          isOpera,
          isSafari,
          isSamsung,
          isUcBrowser,
        }
      }
Run Code Online (Sandbox Code Playgroud)