小编典典

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

javascript

我有5个FF,Chrome,IE,Opera和Safari插件/扩展程序。

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


阅读 669

收藏
2020-04-22

共1个答案

小编典典

谷歌浏览器可靠检测通常会导致检查用户代理字符串。这种方法不可靠,因为欺骗这个值很简单。

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

// 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' && 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;

可靠性分析

在先前的方法依赖于渲染引擎的性质来检测浏览器。这些前缀最终将被删除,因此为了使检测更加可靠,我切换到特定于浏览器的特征:

  • Internet Explorer:JScript的条件编译(直到IE9)和document.documentMode
  • Edge:在Trident和Edge浏览器中,Microsoft的实现公开了StyleMedia构造函数。排除三叉戟使我们陷入困境。
  • 边缘(基于铬):用户代理在末尾包含值“ Edg / [version]”(例如:“ Mozilla / 5.0(Windows NT 10.0; Win64; x64))AppleWebKit / 537.36(KHTML,如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中已修复。因此,我们正在针对SafariRemoteNotification7.1版之后引入的进行检查,以涵盖从3.0版开始的所有Safari。
  • 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+(常绿)。
  • Blink:Google开启Chrome 28后CSS.supports() 在Blink中引入。当然,这与Opera中使用的Blink相同。

在以下方面成功测试:

  • Firefox 0.8-61
  • 铬1.0-71
  • Opera 8.0-34
  • Safari 3.0-10
  • IE 6-11
  • 边缘-20-42
  • Edge开发-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注释)。

2020-04-22