我有5个插件/扩展Firefox, Chrome, Internet Explorer(IE), Opera和Safari。

我如何正确识别用户浏览器和重定向(一旦安装按钮已被点击)下载相应的插件?


google浏览器可靠检测的结果通常是检查User代理字符串。这个方法不可靠,因为欺骗这个值很简单。 我已经编写了一个通过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;

可靠性分析

前一种方法依赖于呈现引擎的属性(-moz-box-sizing和-webkit-transform)来检测浏览器。这些前缀最终将被删除,所以为了使检测更加健壮,我切换到特定于浏览器的特征:

Internet Explorer: JScript's Conditional compilation (up until IE9) and document.documentMode. Edge: In Trident and Edge browsers, Microsoft's implementation exposes the StyleMedia constructor. Excluding Trident leaves us with Edge. Edge (based on chromium): The user agent include the value "Edg/[version]" at the end (ex: "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's API to install add-ons: InstallTrigger Chrome: The global chrome object, containing several properties including a documented chrome.webstore object. Update 3 chrome.webstore is deprecated and undefined in recent versions Safari: A unique naming pattern in its naming of constructors. This is the least durable method of all listed properties and guess what? In Safari 9.1.3 it was fixed. So we are checking against SafariRemoteNotification, which was introduced after version 7.1, to cover all Safaris from 3.0 and upwards. Opera: window.opera has existed for years, but will be dropped when Opera replaces its engine with Blink + V8 (used by Chromium). Update 1: Opera 15 has been released, its UA string looks like Chrome, but with the addition of "OPR". In this version the chrome object is defined (but chrome.webstore isn't). Since Opera tries hard to clone Chrome, I use user agent sniffing for this purpose. Update 2: !!window.opr && opr.addons can be used to detect Opera 20+ (evergreen). Blink: CSS.supports() was introduced in Blink once Google switched on Chrome 28. It's of course, the same Blink used in Opera.

成功测试:

Firefox 0.8 - 61 Chrome 1.0 - 71 Opera 8.0 - 34 Safari 3.0 - 10 Ie 6 - 11 Edge - 20-42 Edge Dev - 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月更新,添加了基于铬检测的Edge(基于@Nimesh评论)。


简单的一行JavaScript代码会告诉你浏览器的名称:

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

您可以尝试以下方法检查浏览器版本。

    <!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>

我知道这可能是使用一个库,但只是为了丰富线程,你可以检查is.js的方式:

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

如果有人觉得这个有用,我已经把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());


以下是2016年Rob的答案调整版本,包括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,它依赖于用户代理嗅探,但是今天(即ver。15岁及以上)甚至Opera本身也只是Blink的一个外壳。


这结合了罗伯的原始答案和皮劳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;

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

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

您可以使用try和catch来使用不同的浏览器错误消息。 IE和edge被混淆了,但我使用了Rob W的duck typing(基于这个项目: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;
        }
    }
};

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

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


还有一种不那么“hack”的方法,适用于所有流行的浏览器。 谷歌在他们的闭包库中包含了一个浏览器检查。特别是,看看goog。userAgent和google .userAgent.product。通过这种方式,如果浏览器显示自身的方式发生了变化(假定您总是运行闭包编译器的最新版本),您也可以了解最新情况。


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',
   });
});

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

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")}


        }

短变体(更新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)

打字文件版本:

export enum BROWSER_ENUM {
  EDGE ,
  INTERNET_EXPLORER ,
  FIRE_FOX ,
  OPERA ,
  UC_BROWSER ,
  SAMSUNG_BROWSER ,
  CHROME ,
  SAFARI ,
  UNKNOWN ,
}

const testUserAgent = (regexp: RegExp): boolean => regexp.test(window.navigator.userAgent);

function detectBrowser(): BROWSER_ENUM {
  switch (true) {
    case testUserAgent(/edg/i): return BROWSER_ENUM.EDGE;
    case testUserAgent(/trident/i): return BROWSER_ENUM.INTERNET_EXPLORER;
    case testUserAgent(/firefox|fxios/i): return BROWSER_ENUM.FIRE_FOX;
    case testUserAgent(/opr\//i): return BROWSER_ENUM.OPERA;
    case testUserAgent(/ucbrowser/i): return BROWSER_ENUM.UC_BROWSER;
    case testUserAgent(/samsungbrowser/i): return BROWSER_ENUM.SAMSUNG_BROWSER;
    case testUserAgent(/chrome|chromium|crios/i): return BROWSER_ENUM.CHROME;
    case testUserAgent(/safari/i): return BROWSER_ENUM.SAFARI;
    default: return BROWSER_ENUM.UNKNOWN;
  }
}

export const BROWSER: BROWSER_ENUM = detectBrowser();

export const IS_FIREFOX = BROWSER === BROWSER_ENUM.FIRE_FOX;

函数式算法,只是为了好玩:

 const BROWSER =  Object.entries({
     "Microsoft Edge": /edg/i,
     "Microsoft Internet Explorer": /trident/i,
     "Mozilla Firefox": /firefox|fxios/i,
     "Opera": /opr\//i,
     "UC Browser": /ucbrowser/i,
     "Samsung Browser": /samsungbrowser/i,
     "Google Chrome": /chrome|chromium|crios/i,
     "Apple Safari": /safari/i,
     "Unknown": /.+/i,
 }).find(([, value]) => value.test(window.navigator.userAgent)).pop();

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

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

var result = bowser.getParser(window.navigator.userAgent); console.log(结果); 文档。write("You are using " + result.parsedResult.browser.name + " v" + result.parsedResult.browser.version + “on”+ result.parsedResult.os.name); < script src = " https://unpkg.com/bowser@2.7.0 es5.js " > < /脚本>

*支持边缘基于铬


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

console.log(平台); 文档。写上("你正在使用" + platform.name + . “V”+平台。版+ “On”+ platform.os); < script src = " https://cdnjs.cloudflare.com/ajax/libs/platform/1.3.5/platform.min.js " > < /脚本>

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

console.log (.browser美元) 文档。写("你正在使用" + $.browser.name + " V " + $.browser。versionNumber + “On”+ $.browser.platform); < script src = " https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js " > < /脚本> < script src = " https://cdnjs.cloudflare.com/ajax/libs/jquery-browser/0.1.0/jquery.browser.min.js " > < /脚本>

Detect.js(存档)by darcyclarke - 522★s -最后更新于2015年10月26日- 2.9KB

var result = detect.parse(navigator.userAgent); console.log(结果); 文档。write("You are using " + result.browser.family + “V”+ result.browser.version + “On”+ result.os.family); < script src = " https://cdnjs.cloudflare.com/ajax/libs/Detect.js/2.2.2/detect.min.js " > < /脚本>

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

console.log (BrowserDetect) 文档。write("You are using " + BrowserDetect. "浏览器+ v + BrowserDetect。版+ “on”+ BrowserDetect.OS); < script src = " https://kylemit.github.io/libraries/libraries/BrowserDetect.js " > < /脚本>


明显的提到:

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

进一步的阅读

堆栈溢出-浏览器检测JavaScript? 堆栈溢出-如何检测浏览器的版本?


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的值。浏览器有条件地编程您的页面。

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


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

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


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

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);
    };

const isChrome = /Chrome/.test(navigator.userAgent)
const isFirefox = /Firefox/.test(navigator.userAgent)

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

从这里获取detect-browser.js

它会给你这样的东西:


简单:

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>');


检测浏览器及其版本

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

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

还做了一些更改来检测Edge和UCBrowser等浏览器

在dev-tools的帮助下,通过更改userAgent来测试以下浏览器的代码(如何更改userAgent):

火狐 铬 即 边缘 歌剧 Safari UCBrowser

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


你可以像这样检测它:

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

这是我定制的解决方案。

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

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

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

OR

var isIE = !!document.documentMode; 

console.log(isIE)

谢谢


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


Chrome & Edge为此引入了一个新的用户代理客户端提示API:

navigator.userAgentData.brands.map(item => item.brand).includes('Google Chrome')

不幸的是,Firefox和Safari还不支持它。


此方法目前对检测所有浏览器有效。我引用vue-element-admin模板

 export function fnBrowserDetect() {
      var browserName = (function(agent) {
        switch (true) {
          case agent.indexOf('edge') > -1: return 'MS Edge'
          case agent.indexOf('edg/') > -1: return 'Edge (chromium based)'
          case agent.indexOf('opr') > -1 && !!window.opr: return 'Opera'
          case agent.indexOf('chrome') > -1 && !!window.chrome: return 'Chrome'
          case agent.indexOf('trident') > -1: return 'MS IE'
          case agent.indexOf('firefox') > -1: return 'Mozilla Firefox'
          case agent.indexOf('safari') > -1: return 'Safari'
          default: return 'other'
        }
      })(window.navigator.userAgent.toLowerCase())
      return browserName.toLowerCase()
    }

var BrowserType; (function (BrowserType) { BrowserType["OPERA"] = "Opera"; BrowserType["OPERA2"] = "OPR"; BrowserType["EDGE"] = "Edg"; BrowserType["CHROME"] = "Chrome"; BrowserType["SAFARI"] = "Safari"; BrowserType["FIREFOX"] = "Firefox"; BrowserType["UNKNOWN"] = "unknown"; })(BrowserType || (BrowserType = {})); const detectBrowser = () => { return Object.values(BrowserType).find((browser) => navigator.userAgent.indexOf(browser) != -1); }; console.log(detectBrowser());