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

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


当前回答

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

其他回答

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

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

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

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

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

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

检测浏览器及其版本

此代码片段基于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());