【问题标题】:How to detect Safari, Chrome, IE, Firefox and Opera browser?如何检测 Safari、Chrome、IE、Firefox 和 Opera 浏览器?
【发布时间】:2012-04-08 12:11:06
【问题描述】:

我有 5 个用于 FF、Chrome、IE、Opera 和 Safari 的插件/扩展。

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

【问题讨论】:

标签: javascript browser-detection


【解决方案1】:

搜索浏览器可靠检测通常会导致检查用户代理字符串。此方法可靠,因为欺骗此值很容易。
我写了一个通过duck-typing检测浏览器的方法。

仅在确实有必要时才使用浏览器检测方法,例如显示特定于浏览器的说明来安装扩展程序。 尽可能使用特征检测。

演示:https://jsfiddle.net/6spj1059/

// 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' && window['safari'].pushNotification));

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

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

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

// Edge (based on chromium) detection
var isEdgeChromium = isChrome && (navigator.userAgent.indexOf("Edg") != -1);

// 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 += 'isEdgeChromium: ' + isEdgeChromium + '<br>';
output += 'isBlink: ' + isBlink + '<br>';
document.body.innerHTML = output;

可靠性分析

previous method 依赖于渲染引擎的属性(-moz-box-sizing-webkit-transform)来检测浏览器。这些前缀最终将被删除,因此为了使检测更加可靠,我切换到浏览器特定的特征:

  • Internet Explorer:JScript 的 Conditional compilation(直到 IE9)和 document.documentMode
  • Edge:在 Trident 和 Edge 浏览器中,Microsoft 的实现公开了 StyleMedia 构造函数。排除 Trident 后,我​​们只剩下 Edge。
  • Edge(基于 chromium):用户代理在末尾包含值“Edg/[version]”(例如:“Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) ) Chrome/80.0.3987.16 Safari/537.36 Edg/80.0.361.9")。
  • Firefox:Firefox 用于安装附加组件的 API:InstallTrigger
  • Chrome:全局 chrome 对象,包含多个属性,包括记录在案的 chrome.webstore 对象。
  • Update 3 chrome.webstore 在最新版本中已弃用且未定义
  • Safari:构造函数命名中的独特命名模式。这是所有列出的属性中最不耐用的方法,你猜怎么着?在 Safari 9.1.3 中已修复。因此,我们正在检查 7.1 版之后引入的 SafariRemoteNotification,以涵盖 3.0 及更高版本的所有 Safari。
  • Opera:window.opera 已存在多年,但当 Opera 将其引擎替换为 Blink + V8(由 Chromium 使用)时,will be dropped
  • 更新 1:Opera 15 has been released,它的 UA 字符串看起来像 Chrome,但添加了“OPR”。在这个版本中,chrome 对象被定义(但chrome.webstore 没有)。由于 Opera 试图克隆 Chrome,我为此使用了用户代理嗅探。
  • 更新 2:!!window.opr &amp;&amp; opr.addons 可用于检测 Opera 20+(常绿)。
  • Blink:CSS.supports()was introduced in Blink Google 开启 Chrome 28 后。当然,与 Opera 中使用的 Blink 相同。

成功测试:

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

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

于 2018 年 8 月更新,以更新在 chrome、firefox IE 和 edge 上的最新成功测试。

于 2019 年 1 月更新以修复 chrome 检测(由于 window.chrome.webstore 已弃用)并包含最新的成功测试 chrome。

于 2019 年 12 月更新,添加了基于 Chromium 检测的 Edge(基于 @Nimesh 评论)。

【讨论】:

  • 仅供参考,这不适用于 Chrome 扩展,因为 window.chrome.webstore 在那里未定义。没有用 Firefox 扩展检查它。 is.js 在其他地方提到的确实适用于 Chrome 和 Firefox 扩展。
  • isSafari 不适用于 Safari 10。我认为这是一个糟糕的解决方案(并不是说我有一个好的解决方案)。无法保证您检查的许多内容不会被删除或不会被其他浏览器添加。每个使用此代码检查 Safari 的网站都因 macOS Sierra 或 Safari 10 升级而中断:(
  • 但这是否已经在这些浏览器的移动版本以及桌面版本上进行了测试?老实说,每个平台都有不同的移动版本和不同的桌面版本。真的,firefox 有 3 个适用于 Windows、Linux、Mac OS 的二进制文件,以及 2 个适用于 Android 和 iOS 的二进制文件。
  • 当前isSafari在Safari 10.1.2下&lt;iframe&gt;下不起作用
  • window.chrome.webstore 从 Chrome 版本开始已弃用。 71:blog.chromium.org/2018/06/…
【解决方案2】:

简单的单行 JavaScript 代码将为您提供浏览器的名称:

function GetBrowser()
{
    return  navigator ? navigator.userAgent.toLowerCase() : "other";
}

【讨论】:

  • 仅 userAgent 并不能告诉我们足够的信息。例如,我的用户代理是“Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.85 Safari/537.36”,其中提到了 Mozilla、Chrome 和 Safari。我是哪种浏览器?
  • 抱歉,我没有找到“我是哪种浏览器类型?”你想得到什么?
  • @NiravMehta 他的意思是navigator.userAgent 告诉你可能拥有的每一个浏览器。所以这真的不可靠,唯一可行的情况是用户只有一个浏览器。
  • 这不是检测浏览器的可靠方法。一些用户代理同时包含 chrome 和 safari,因此无法检测我们应该考虑哪一个和最后一个,但并非最不重要的是,用户代理可以通过网页进行修改。
【解决方案3】:

您可以尝试以下方式查看浏览器版本。

    <!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("Edg") != -1 )
    {
        alert('Edge');
    }
    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>

如果您只需要知道 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>

【讨论】:

  • 为什么要写这么多行代码? userAgent 不明确。
  • Microsoft Edge 怎么样?
  • 在检查 safari 之前,上面的答案会检查 chrome。因为 safari 在用户代理中不会有 chrome 关键字。 Safari 用户代理示例 - 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
  • Stackoverflow 使用这种方法
  • 在 Opera(最新版本)中测试时,这会为我返回“Chrome”。为了解决这个问题,我将 Opera if 语句更改为:if(navigator.userAgent.indexOf("Opera") != -1 || navigator.userAgent.indexOf('OPR') != -1 )
【解决方案4】:

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

is.firefox();
is.ie(6);
is.not.safari();

【讨论】:

  • 值得注意的是,它在底层主要是进行用户代理检测。补充供应商检测/某些地方的特征检测。
  • @TygerKrash 当然,你是绝对正确的。这实际上是我回答的意思:打开is.js 的源代码并检查他们是如何做到的。
  • jQuery 曾经包含类似的属性:$.browser.msie... 已从 1.9 版中删除api.jquery.com/jquery.browser
  • @RafaelEyng:我认为它进行用户代理检测的问题在于这种方法不可靠。
  • 当您假设 UA 字符串未被修改时,这绝对是最可靠的方法。它还可以正确检测操作系统(android、win、mac、linux);设备类型(台式机、平板电脑、移动设备)。它还可以测试浏览器的版本。
【解决方案5】:

如果有人觉得这很有用,我已经将Rob W's answer 变成了一个返回浏览器字符串的函数,而不是让多个变量浮动。由于浏览器在不重新加载的情况下也无法真正更改,因此我将其缓存结果以防止它在下次调用该函数时需要解决。

/**
 * 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());

【讨论】:

  • 在Edge浏览器中,返回Chrome
  • @eFriend 我更新了最新浏览器测试的答案。
  • 我喜欢这个,但我宁愿回退到 userAgent(),而不是“不知道”。
  • Property window.chrome.webstore 在 Chrome 71 中已被删除,因此这种方法不再有效。
  • 你可以用一个简单地返回 cachedResult 并省略 if 语句的函数来覆盖该函数。第一次你仍然必须返回结果。浏览器=函数(){返回缓存结果};返回缓存结果;
【解决方案6】:

这是 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);

这种方法的美妙之处在于它依赖于浏览器引擎属性,因此它甚至涵盖衍生浏览器,例如 Yandex 或 Vivaldi,它们实际上与它们使用的引擎的主要浏览器兼容。 Opera 是个例外,它依赖于用户代理嗅探,但今天(即 15 版及更高版本)甚至 Opera 本身也只是 Blink 的一个外壳。

【讨论】:

  • !!window.MSAssertion; 测试不适用于我在 Edge 测试版中通过远程桌面进行的操作。它返回 false。
  • @NoR 您使用的是什么版本的 Edge?很重要
  • @NoR 哦,你正在使用虚拟机...MSAssertion 技巧已调整为版本 25。但由于许多开发人员依赖虚拟机,我会尝试将其调整为旧版本.好决定。谢谢。
  • @NoR 已更新 - 应该是面向未来的。 StyleMedia(大写)对象是特定于 IE 和 Edge 的,似乎不会出现在任何地方。
  • 我还发现了UAParser 一个 js 插件,它仍然在维护,并且非常准确且易于使用。
【解决方案7】:

This 结合了 Rob 的原始答案和 Pilau 的 2016 年更新

    var isOpera = !!window.opera || navigator.userAgent.indexOf(' OPR/') >= 0;
    // Opera 8.0+ (UA detection to detect Blink/v8-powered Opera)
var isFirefox = typeof InstallTrigger !== 'undefined';   // Firefox 1.0+
var isSafari = Object.prototype.toString.call(window.HTMLElement).indexOf('Constructor') > 0;
    // At least Safari 3+: "[object HTMLElementConstructor]"
var isChrome = !!window.chrome && !isOpera;              // Chrome 1+
var isIE = /*@cc_on!@*/false || !!document.documentMode;
// Edge 20+
var isEdge = !isIE && !!window.StyleMedia;
// Chrome 1+
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 += 'isIE Edge: ' + isEdge + '<br>';
document.body.innerHTML = output;

【讨论】:

  • 告诉用户他们使用的是什么浏览器有什么意义吗?我想他们应该已经知道了。
  • @HoldOffHunger 的主要目的是让最兼容的代码适应活动的浏览器,而不是通知用户他们正在使用哪个浏览器。除非他们使用的浏览器已经过时并且被排除在向后兼容性之外,否则让用户知道他们可以从更好的体验中受益,如果他们切换到更新的东西
【解决方案8】:

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

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

【讨论】:

    【解决方案9】:

    您可以使用trycatch 来使用不同的浏览器错误消息。 IE 和 edge 混淆了,但我使用了 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;
            }
        }
    };
    

    【讨论】:

    • 这是个好主意:您不需要“窗口”和“导航器”对象!
    • 我的建议是彻底摆脱文档和窗口。参见 IE 块:返回“firefox”; } else if(err.search("[object Error]") !== -1 && e.message != null && e.description != null){ return "IE"; } else if(err.search("cannot convert e into object") !== -1){ return "opera";
    • IE 和 edge 有什么区别?
    • 奇怪,我不能再重现 err.search("[object Error]") 了。无论如何,对我来说,firefox vs chrome vs 其他东西就足够了。我在窗口和文档对象不可用的 PAC 文件中使用它。
    • 刚刚找出原因。看起来 Windows 7 不使用安装在我机器上的 IE11,而是使用类似 IE7 的引擎(可能来自 Windows 主机)来玩 PAC 文件。所以 err.toString() 给出了“[object Error]”,而在 IE11 中它给出了“Unable to get property...”字符串,就像你的代码一样。所以,上面的代码在 IE7 下应该会失败。
    【解决方案10】:

    谢谢大家。我在最近的浏览器上测试了代码 sn-ps: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);
    

    它在 HTML 中添加了一个 CSS 类,带有浏览器的名称。

    【讨论】:

    • 你在ios上测试过chrome吗?
    【解决方案11】:

    还有一种适用于所有流行浏览器的“hacky”方法。 Google 在其Closure Library 中包含了浏览器检查功能。特别是,看看goog.userAgentgoog.userAgent.product。通过这种方式,如果浏览器呈现自身的方式发生变化,您也可以保持最新状态(假设您始终运行最新版本的闭包编译器。)

    【讨论】:

    • 如果它们是唯一可靠的方法,这里的大多数答案都不关心“hacky”。正如多次提到的,userAgent 很容易被欺骗,因此不可靠。
    【解决方案12】:
    var BrowserDetect = {
            init: function () {
                this.browser = this.searchString(this.dataBrowser) || "Other";
                this.version = this.searchVersion(navigator.userAgent) || this.searchVersion(navigator.appVersion) || "Unknown";
            },
            searchString: function (data) {
                for (var i = 0; i < data.length; i++) {
                    var dataString = data[i].string;
                    this.versionSearchString = data[i].subString;
    
                    if (dataString.indexOf(data[i].subString) !== -1) {
                        return data[i].identity;
                    }
                }
            },
            searchVersion: function (dataString) {
                var index = dataString.indexOf(this.versionSearchString);
                if (index === -1) {
                    return;
                }
    
                var rv = dataString.indexOf("rv:");
                if (this.versionSearchString === "Trident" && rv !== -1) {
                    return parseFloat(dataString.substring(rv + 3));
                } else {
                    return parseFloat(dataString.substring(index + this.versionSearchString.length + 1));
                }
            },
    
            dataBrowser: [
                {string: navigator.userAgent, subString: "Edge", identity: "MS Edge"},
                {string: navigator.userAgent, subString: "MSIE", identity: "Explorer"},
                {string: navigator.userAgent, subString: "Trident", identity: "Explorer"},
                {string: navigator.userAgent, subString: "Firefox", identity: "Firefox"},
                {string: navigator.userAgent, subString: "Opera", identity: "Opera"},  
                {string: navigator.userAgent, subString: "OPR", identity: "Opera"},  
    
                {string: navigator.userAgent, subString: "Chrome", identity: "Chrome"}, 
                {string: navigator.userAgent, subString: "Safari", identity: "Safari"}       
            ]
        };
    
        BrowserDetect.init();
    
    
        var bv= BrowserDetect.browser;
        if( bv == "Chrome"){
            $("body").addClass("chrome");
        }
        else if(bv == "MS Edge"){
         $("body").addClass("edge");
        }
        else if(bv == "Explorer"){
         $("body").addClass("ie");
        }
        else if(bv == "Firefox"){
         $("body").addClass("Firefox");
        }
    
    
    $(".relative").click(function(){
    $(".oc").toggle('slide', { direction: 'left', mode: 'show' }, 500);
    $(".oc1").css({
       'width' : '100%',
       'margin-left' : '0px',
       });
    });
    

    【讨论】:

      【解决方案13】:

      在这里您可以找到它正在运行的浏览器。

      function isValidBrowser(navigator){
      
                  var isChrome =  navigator.indexOf('chrome'),
                  isFireFox= navigator.indexOf('firefox'),
                  isIE = navigator.indexOf('trident') ,
                  isValidChromeVer = parseInt(navigator.substring(isChrome+7, isChrome+8)) >= 4,
                  isValidFireForVer = parseInt(navigator.substring(isFireFox+8, isFireFox+9)) >= 3,
                  isValidIEVer = parseInt(navigator.substring(isIE+8, isIE+9)) >= 7;
      
                  if((isChrome > -1 && isValidChromeVer){ console.log("Chrome Browser")}
      
                  if(isFireFox > -1 && isValidFireForVer){ console.log("FireFox  Browser")}
      
                  if(isIE > -1 && isValidIEVer)){ console.log("IE Browser")}
      
      
              }
      

      【讨论】:

        【解决方案14】:

        短变体(2020 年 7 月 10 日更新移动浏览器检测修复

        var browser = (function() {
            var test = function(regexp) {return regexp.test(window.navigator.userAgent)}
            switch (true) {
                case test(/edg/i): return "Microsoft Edge";
                case test(/trident/i): return "Microsoft Internet Explorer";
                case test(/firefox|fxios/i): return "Mozilla Firefox";
                case test(/opr\//i): return "Opera";
                case test(/ucbrowser/i): return "UC Browser";
                case test(/samsungbrowser/i): return "Samsung Browser";
                case test(/chrome|chromium|crios/i): return "Google Chrome";
                case test(/safari/i): return "Apple Safari";
                default: return "Other";
            }
        })();
        console.log(browser)

        【讨论】:

        • 如果你不喜欢我,请解释原因。
        • 这将在 ios 上使用“chrome”浏览时显示“safari”
        • 此方法适用于桌面上的 Chrome 和 Firefox 以及 iOS 上的 Safari。它在 iOS 上的 Chrome 和 Firefox 上失败。
        • @BReddy 请重新测试一下,我没有任何苹果设备:)
        • 我在 Firefox(Win10 上为 78.0.1)、Chrome(Win10 上为 83.0)、Edge(Win10 上为 83.0 - Chromium 基础)、Firefox(iOS 上为 27)和 Chrome(83.0 上)对此进行了测试iOS) 成功。此逻辑仍报告 Safari(在 iOS 13.5.1 上)仍报告为“chrome”。这可能是因为 Chromium 是从 WebKit 基础派生的吗?
        【解决方案15】:

        以下是截至 2019 年 12 月处理浏览器检测的几个著名库。

        Bowser by lancedikson - 4,065★s - 最后更新于 2019 年 10 月 2 日 - 4.8KB

        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);
        &lt;script src="https://unpkg.com/bowser@2.7.0/es5.js"&gt;&lt;/script&gt;

        *支持基于 Chromium 的 Edge


        Platform.js by bestiejs - 2,550★s - 最后更新于 2019 年 4 月 14 日 - 5.9KB

        console.log(platform);
        document.write("You are using " + platform.name +
                       " v" + platform.version + 
                       " on " + platform.os);
        &lt;script src="https://cdnjs.cloudflare.com/ajax/libs/platform/1.3.5/platform.min.js"&gt;&lt;/script&gt;

        jQuery Browser 来自 gabceb - 504★s - 最后更新于 2015 年 11 月 23 日 - 1.3KB

        console.log($.browser)
        document.write("You are using " + $.browser.name +
                       " v" + $.browser.versionNumber + 
                       " on " + $.browser.platform);
        <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>

        Detect.js (Archived) 由 darcyclarke - 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);
        &lt;script src="https://cdnjs.cloudflare.com/ajax/libs/Detect.js/2.2.2/detect.min.js"&gt;&lt;/script&gt;

        Browser Detect (Archived) 来自 QuirksMode - 最后更新于 2013 年 11 月 14 日 - 884B

        console.log(BrowserDetect)
        document.write("You are using " + BrowserDetect.browser +
                       " v" + BrowserDetect.version + 
                       " on " + BrowserDetect.OS);
        &lt;script src="https://kylemit.github.io/libraries/libraries/BrowserDetect.js"&gt;&lt;/script&gt;

        值得注意的提及:

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

        进一步阅读

        【讨论】:

        • 为了不重新发明轮子而花费几 Kb 的开销是值得的。
        【解决方案16】:

        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>
        

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

        源码教程:How to detect browser, engine, OS, CPU, and device using JavaScript?

        【讨论】:

        • 你称之为轻量级的thousand 行代码?
        【解决方案17】:

        不知道它是否对任何人有用,但这里有一个变体可以让 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';
            }
        }
        

        【讨论】:

        • 为什么你有一些以“假”为条件的ifs?
        • @YonatanNir 我认为这是为了检测条件编译:developer.mozilla.org/en-US/docs/Web/JavaScript/…
        • Typescript 与此相同:Argument of type '{ new (): HTMLElement;原型:HTML元素; }' 不可分配给“字符串”类型的参数
        【解决方案18】:

        检测桌面和移动浏览器: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';
            }
        }
        

        感谢@nimesh 用户:2063564

        【讨论】:

        • 当我在 Chrome 中时它正在启动 Safari...
        【解决方案19】:

        我们可以使用下面的实用方法

        utils.isIE = function () {
                var ver = navigator.userAgent;
                return ver.indexOf("MSIE") !== -1 || ver.indexOf("Trident") !== -1; // need to check for Trident for IE11
            };
        
            utils.isIE32 = function () {
                return (utils.isIE() && navigator.appVersion.indexOf('Win64') === -1);
            };
        
            utils.isChrome = function () {
                return (window.chrome);
            };
        
            utils.isFF64 = function () {
                var agent = navigator.userAgent;
                return (agent.indexOf('Win64') >= 0 && agent.indexOf('Firefox') >= 0);
            };
        
            utils.isFirefox = function () {
                return (navigator.userAgent.toLowerCase().indexOf('firefox') > -1);
            };
        

        【讨论】:

          【解决方案20】:
          const isChrome = /Chrome/.test(navigator.userAgent)
          const isFirefox = /Firefox/.test(navigator.userAgent)
          

          【讨论】:

          • 不幸的是,这不是一个好的答案。 Edge 在他的 userAgent 消息中有 Chrome。最好用!!window.chrome && (!!window.chrome.webstore || !!window.chrome.runtime);
          • 您的回答对于 Opera 浏览器也失败了
          【解决方案21】:

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

          从这里获取它detect-browser.js

          它会给你类似的东西:

          【讨论】:

            【解决方案22】:

            简单:

            var OSName="Unknown OS";
            if (navigator.appVersion.indexOf("Win")!=-1) OSName="Windows";
            if (navigator.appVersion.indexOf("Mac")!=-1) OSName="MacOS";
            if (navigator.appVersion.indexOf("X11")!=-1) OSName="UNIX";
            if (navigator.appVersion.indexOf("Linux")!=-1) OSName="Linux";
            if (navigator.appVersion.indexOf("Linux x86_64")!=-1) OSName="Ubuntu";
            
            var nVer = navigator.appVersion;
            var nAgt = navigator.userAgent;
            var browserName  = navigator.appName;
            var fullVersion  = ''+parseFloat(navigator.appVersion); 
            var majorVersion = parseInt(navigator.appVersion,10);
            var nameOffset,verOffset,ix;
            
            // In Opera, the true version is after "Opera" or after "Version"
            if ((verOffset=nAgt.indexOf("Opera"))!=-1) {
             browserName = "Opera";
             fullVersion = nAgt.substring(verOffset+6);
             if ((verOffset=nAgt.indexOf("Version"))!=-1) 
               fullVersion = nAgt.substring(verOffset+8);
            }
            // In MSIE, the true version is after "MSIE" in userAgent
            else if ((verOffset=nAgt.indexOf("MSIE"))!=-1) {
             browserName = "Microsoft Internet Explorer";
             fullVersion = nAgt.substring(verOffset+5);
            }
            // In Chrome, the true version is after "Chrome" 
            else if ((verOffset=nAgt.indexOf("Chrome"))!=-1) {
             browserName = "Chrome";
             fullVersion = nAgt.substring(verOffset+7);
            }
            // In Safari, the true version is after "Safari" or after "Version" 
            else if ((verOffset=nAgt.indexOf("Safari"))!=-1) {
             browserName = "Safari";
             fullVersion = nAgt.substring(verOffset+7);
             if ((verOffset=nAgt.indexOf("Version"))!=-1) 
               fullVersion = nAgt.substring(verOffset+8);
            }
            // In Firefox, the true version is after "Firefox" 
            else if ((verOffset=nAgt.indexOf("Firefox"))!=-1) {
             browserName = "Firefox";
             fullVersion = nAgt.substring(verOffset+8);
            }
            // In most other browsers, "name/version" is at the end of userAgent 
            else if ( (nameOffset=nAgt.lastIndexOf(' ')+1) < 
                      (verOffset=nAgt.lastIndexOf('/')) ) 
            {
             browserName = nAgt.substring(nameOffset,verOffset);
             fullVersion = nAgt.substring(verOffset+1);
             if (browserName.toLowerCase()==browserName.toUpperCase()) {
              browserName = navigator.appName;
             }
            }
            // trim the fullVersion string at semicolon/space if present
            if ((ix=fullVersion.indexOf(";"))!=-1)
               fullVersion=fullVersion.substring(0,ix);
            if ((ix=fullVersion.indexOf(" "))!=-1)
               fullVersion=fullVersion.substring(0,ix);
            
            majorVersion = parseInt(''+fullVersion,10);
            if (isNaN(majorVersion)) {
             fullVersion  = ''+parseFloat(navigator.appVersion); 
             majorVersion = parseInt(navigator.appVersion,10);
            }
            
            document.write(''
             +'Hey! i see you\'re using '+browserName+'! <br>'
             +'The full version of it is '+fullVersion+'. <br>'
             +'Your major version is '+majorVersion+', <br>'
             +'And your "navigator.appName" is '+navigator.appName+'. <br>'
             +'Your "navigator.userAgent" is '+navigator.userAgent+'. <br>'
            )
            
            document.write('And, your OS is '+OSName+'. <br>');

            【讨论】:

            • 我来自 android,使用 microsoft edge 浏览器。你的代码说我是“ubuntu with chrome”
            【解决方案23】:

            检测浏览器及其版本

            这段代码sn-p是基于MDN的文章。他们提供了有关可用于检测浏览器名称的各种关键字的简要提示。

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

            还进行了一些更改以检测 EdgeUCBrowser

            等浏览器

            目前在开发工具 (How to change 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());

            【讨论】:

              【解决方案24】:

              你可以像这样检测它:

              if (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)) {
                 alert('Firefox');
              }
              

              【讨论】:

                【解决方案25】:

                这是我的定制解决方案。

                        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,
                        }
                      }
                

                【讨论】:

                  【解决方案26】:

                  使用以下代码检查 IE 浏览器。

                  console.log(/MSIE|Trident/.test(window.navigator.userAgent))
                  

                  var isIE = !!document.documentMode; 
                  
                  console.log(isIE)
                  

                  谢谢

                  【讨论】:

                    【解决方案27】:
                    import getAgent, { getAccurateAgent } from "@egjs/agent";
                    
                    const agent = getAgent();
                    getAccurateAgent().then((accurate_agent)=>{
                        console.log(agent,'accurate.');
                    })
                    console.log(agent);
                    

                    https://github.com/naver/egjs-agent

                    【讨论】:

                      猜你喜欢
                      • 2022-12-24
                      • 2015-03-26
                      • 1970-01-01
                      • 2019-02-03
                      • 2012-09-19
                      • 2010-09-12
                      • 2012-08-08
                      相关资源
                      最近更新 更多