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

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

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

1157543 次浏览

谷歌搜索浏览器可靠检测通常会导致检查User代理字符串。此方法没有可靠,因为欺骗此值很简单。
我写了一个方法来检测浏览器鸭子打字

只有在真正必要时才使用浏览器检测方法,例如显示浏览器特定的指令来安装扩展。尽可能使用特征检测。

演示: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-11var isIE = /*@cc_on!@*/false || !!document.documentMode;
// Edge 20+var isEdge = !isIE && !!window.StyleMedia;
// Chrome 1 - 79var isChrome = !!window.chrome && (!!window.chrome.webstore || !!window.chrome.runtime);
// Edge (based on chromium) detectionvar isEdgeChromium = isChrome && (navigator.userAgent.indexOf("Edg") != -1);
// Blink engine detectionvar 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;

可靠性分析

以前的方法依赖于渲染引擎的属性(#0-webkit-transform)来检测浏览器。这些前缀最终会被删除,所以为了使检测更加健壮,我切换到浏览器特定的特性:

  • Internet Explorer:JScript的条件编译(直到IE9)和#0
  • Edge:在三叉戟和Edge浏览器中,Microsoft的实现公开了StyleMedia构造函数。排除三叉戟让我们使用Edge。
  • Edge(基于chromium):用户代理在末尾包含值“Edg/[version]”(例如:“Mozilla/5.0(Windows NT 10.0; Win64; x64)AppleWebKit/537.36(KHTML,如Gecko)Chrome /80.0.3987.16Safari /537.36Edg/80.0.361.9”)。
  • Firefox:Firefox安装附加组件的API:#0
  • Chrome:全局chrome对象,包含多个属性,包括记录的#1对象。
  • Update 3chrome.webstore在最新版本中已弃用且未定义
  • Safari:构造函数命名中的独特命名模式。这是所有列出的属性中最不持久的方法,猜猜是什么?在9.1.3Safari它被修复了。所以我们正在检查7.1版之后引入的SafariRemoteNotification,以涵盖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+(常绿)。
  • 眨眼:CSS.supports()在Blink中引入一旦谷歌打开了Chrome28。当然,它与Opera中使用的眨眼相同。

测试成功:

  • Firefox 0.8-61
  • Chrome1.0-71
  • Opera 8.0-34
  • Safari3.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检测的边缘(基于@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 < IE11alert(parseInt(ua.substring(msie + 5, ua.indexOf(".", msie))));}return false;}}</script>
</body></html>

我知道使用lib可能有点矫枉过正,但为了丰富线程,您可以检查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-11var isIE = /*@cc_on!@*/false || !!document.documentMode;
// Edge 20+var isEdge = !isIE && !!window.StyleMedia;
// Chrome 1+var isChrome = !!window.chrome && !!window.chrome.webstore;
// Blink engine detectionvar 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());

以下是Rob答案的2016年调整版本,包括Microsoft Edge和眨眼检测:

编辑:我用这些信息更新了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-11isIE = /*@cc_on!@*/false || !!document.documentMode;// Edge 20+isEdge = !isIE && !!window.StyleMedia;// Chrome 1+isChrome = !!window.chrome && !!window.chrome.webstore;// Blink engine detectionisBlink = (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的外壳。

这个结合了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;

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

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

您可以使用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;}}};

谢谢大家。我在最近的浏览器上测试了代码片段:Chrome55,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类,带有浏览器的名称。

还有一个不那么“hacky”的方法适用于所有流行的浏览器。谷歌在他们的闭包库中包含了浏览器检查。特别是,看看#0#1。通过这种方式,如果浏览器呈现自己的方式发生了变化,你也是最新的(假设你总是运行最新版本的闭包编译器。)

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)

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

Bowser by lance dikson-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);
<script src="https://unpkg.com/bowser@2.7.0/es5.js"></script>

*supports Edge based on Chromium


Platform.js by bestiejs - 2,550★s - Last updated Apr 14, 2019 - 5.9KB

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

jQuery Browser by gabceb - 504★s - Last updated Nov 23, 2015 - 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(存档) by dar的arke-522★s-最后更新Oct 26,2015-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);
<script src="https://cdnjs.cloudflare.com/ajax/libs/Detect.js/2.2.2/detect.min.js"></script>

Browser Detect (Archived) by QuirksMode - Last updated Nov 14, 2013 - 884B

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


Notable Mentions:

  • WhichBrowser - 1,355★s - Last updated Oct 2, 2018
  • Modernizr - 23,397★s - Last updated Jan 12, 2019 - To feed a fed horse, feature detection should drive any canIuse style questions. Browser detection is really just for providing customized images, download files, or instructions for individual browsers.

Further Reading

UAParser是一个JavaScript库,用于从userAgent字符串中识别浏览器、引擎、OS、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的值来有条件地对页面进行编程。

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

不知道它是否对任何人有用,但这里有一个让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-11if (/*@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 detectionif (((!!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 user: 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库来检测和打印浏览器信息对象,包括浏览器语言/名称、用户代理、设备类型、用户操作系统、引用、在线/0ffline、用户时区、屏幕分辨率和启用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 userAgentelse 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 userAgentelse 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 presentif ((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。

还做了一些更改来检测EdgeUCBrowser等浏览器

该代码目前通过在开发工具(如何更改userAgent)的帮助下更改userAgent来测试以下浏览器:

  • FireFox
  • Chrome
  • IE
  • Edge
  • Opera
  • Safari
  • UCBrowser

getBrowser = () => {const userAgent = navigator.userAgent;let browser = "unkown";// Detect browser namebrowser = (/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 versionswitch (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.0return 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') > 0const 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))

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为此推出了新的User-Agent客户端提示API

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

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