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

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


当前回答

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

其他回答

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评论)。

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

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

从这里获取detect-browser.js

它会给你这样的东西:

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

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

此方法目前对检测所有浏览器有效。我引用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()
    }