如何确定您的扩展后台脚本正在哪个浏览器中执行?

zhm*_*zhm 8 javascript google-chrome-extension opera-extension firefox-addon-webextensions microsoft-edge-extension

我说的是 Chrome 扩展程序、Firefox WebExtensions、Edge 扩展程序……

在后台脚本而不是内容脚本中,是否有一种明确的方法可以知道我使用的是哪个浏览器?我需要对不同的浏览器做不同的操作。

是的,navigator.userAgent可能有用,但不是很清楚

是否有任何扩展 API 可用于执行此操作?类似的东西,chrome.extension.browserType。(当然,这个真的不存在..)

Mak*_*yen 7

没有特定的 API 来检测当前正在使用的浏览器。主要浏览器转向支持通用扩展框架的好处之一是能够拥有支持多个浏览器的单一代码库。虽然可从所有适用浏览器获得的功能集不断增加,但总会存在一些差异。这些差异不仅在于支持的内容,而且在某些情况下还在于特定 API 的效果细节,或必须如何使用 API。1, 2因此,对于某些事情,必须能够确定代码当前运行的是哪个浏览器。

“如何检测 Safari、Chrome、IE、Firefox 和 Opera 浏览器?”最高投票答案中有一些很好的代码可用。. 但是,它需要一些修改才能在扩展环境中工作。

根据该答案中的代码,将检测以下内容:

  • 铬合金
  • 边缘
  • 火狐
  • 歌剧
  • 宾克引擎
// Opera 8.0+ (tested on Opera 42.0)
var isOpera = (!!window.opr && !!opr.addons) || !!window.opera 
                || navigator.userAgent.indexOf(' OPR/') >= 0;

// Firefox 1.0+ (tested on Firefox 45 - 53)
var isFirefox = typeof InstallTrigger !== 'undefined';

// Internet Explorer 6-11
//   Untested on IE (of course). Here because it shows some logic for isEdge.
var isIE = /*@cc_on!@*/false || !!document.documentMode;

// Edge 20+ (tested on Edge 38.14393.0.0)
var isEdge = !isIE && !!window.StyleMedia;

// Chrome 1+ (tested on Chrome 55.0.2883.87)
// This does not work in an extension:
//var isChrome = !!window.chrome && !!window.chrome.webstore;
// The other browsers are trying to be more like Chrome, so picking
// capabilities which are in Chrome, but not in others is a moving
// target.  Just default to Chrome if none of the others is detected.
var isChrome = !isOpera && !isFirefox && !isIE && !isEdge;

// Blink engine detection (tested on Chrome 55.0.2883.87 and Opera 42.0)
var isBlink = (isChrome || isOpera) && !!window.CSS;

/* The above code is based on code from: https://stackoverflow.com/a/9851769/3773011 */    
//Verification:
var log = console.log;
if(isEdge) log = alert; //Edge console.log() does not work, but alert() does.
log('isChrome: ' + isChrome);
log('isEdge: ' + isEdge);
log('isFirefox: ' + isFirefox);
log('isIE: ' + isIE);
log('isOpera: ' + isOpera);
log('isBlink: ' + isBlink);
Run Code Online (Sandbox Code Playgroud)
  1. API 的不同实现与不同浏览器等复杂多样的东西交互,最终总是会在实现之间至少存在细微的差异。目前,许多差异并不那么微妙。
  2. Mozilla 明确表示,他们打算通过扩展chrome.*/ browser.*API来实现当前在其他浏览器中不可用的 WebExtensions 功能。这样做的一种方法是有一种称为WebExtensions Experiments的机制,旨在供非 Mozilla 开发人员为 WebExtensions 实现附加功能。其目的是,如果获得批准,此类功能将迁移到 Firefox 版本中。