action.setBadgeBackgroundColor()

设置徽章的背景颜色。没有指定徽章背景颜色的标签页将继承全局徽章背景颜色(在 Firefox 中默认为 [217, 0, 0, 255])。

备注: 该 API 在 Manifest V3 或更高版本中可用。

在 Firefox 中,除非使用 action.setBadgeTextColor() 明确设置徽章文本颜色,否则徽章文本颜色会自动设置为黑色或白色,以最大程度与指定的徽章背景颜色形成对比。例如,如果将徽章背景颜色设置为白色,则默认的徽章文本颜色将设置为黑色,反之亦然。

在其他浏览器中,徽章文本颜色始终为白色,因此设置深色的背景颜色更合适:这样能确保文本的可读性。

语法

js
browser.action.setBadgeBackgroundColor(
  details // 对象
)

参数

details

一个含有下列属性的对象:

color

颜色,指定为以下之一:

  • 字符串:任意 CSS <color> 值,例如 "red""#FF0000""rgb(255 0 0)"。若字符串不是一个正确的颜色,则 Promise 会被拒绝且背景颜色不会被更改。
  • action.ColorArray 对象。
  • null,若指定了 tabId,则会移除该标签页的徽章背景颜色,让标签页继承全局徽章背景颜色;反之,会撤销对全局徽章背景颜色的修改使之变回默认取值。
tabId 可选

integer,指定要设置徽章背景颜色的标签页。当用户导航到新页面的时候,背景颜色将被重置。

windowId 可选

integer,指定要设置徽章背景颜色的窗口。

  • 若同时指定了 windowIdtabId,则函数出错且并不会设置颜色。
  • 若同时未指定 windowIdtabId,则将设置全局徽章背景颜色。

示例

背景颜色最初设置为红色,并且当浏览器操作被单击时变为绿色:

js
browser.action.setBadgeText({ text: "1234" });
browser.action.setBadgeBackgroundColor({ color: "red" });

browser.action.onClicked.addListener(() => {
  browser.action.setBadgeBackgroundColor({ color: "green" });
});

仅为活动标签页设置背景颜色:

js
browser.action.setBadgeText({ text: "1234" });
browser.action.setBadgeBackgroundColor({ color: "red" });

browser.action.onClicked.addListener((tab) => {
  browser.action.setBadgeBackgroundColor({
    color: "green",
    tabId: tab.id,
  });
});

浏览器兼容性

Report problems with this compatibility data on GitHub
desktopmobile
Chrome
Edge
Firefox
Opera
Safari
Firefox for Android
Safari on iOS
setBadgeBackgroundColor
details.windowId parameter
The color property of the details parameter can be set to null.
The color property of the details parameter can be set to a string.

Legend

Tip: you can click/tap on a cell for more information.

Full support
Full support
Partial support
Partial support
No support
No support

Firefox 的默认颜色是 [217, 0, 0, 255]

备注: 该 API 基于 Chromium 的 chrome.action API。本文衍生自 Chromium 代码中的 browser_action.json