通知

通知允许您使用底层操作系统提供的通知服务来传达有关您的扩展或其内容的信息。

Example notification on macOS, located below the system clock, with a bold title reading "Click notification" followed by regular text reading "You clicked https://mdn.org.cn/en-US/docs/MDN". The notification has the Firefox Nightly logo on the left side, and a link icon on the right.

通知可以包含用户采取行动的号召,并且您的插件可以监听用户点击通知或通知关闭的事件。

指定通知

您通过编程方式管理通知,使用 notifications API。要使用此 API,您必须在 manifest.json 中请求 notifications 权限。

json
"permissions": ["notifications"]

然后,您可以使用 notifications.create 来创建通知,如下面的来自 notify-link-clicks-i18n: 的示例:

js
const title = browser.i18n.getMessage("notificationTitle");
const content = browser.i18n.getMessage("notificationContent", message.url);
browser.notifications.create({
  type: "basic",
  iconUrl: browser.extension.getURL("icons/link-48.png"),
  title,
  message: content,
});

此代码创建一个带有图标、标题和消息的通知。

如果通知包含行动号召,您可以监听用户点击通知的事件,然后调用相应的函数来处理该行动。

js
browser.notifications.onClicked.addListener(handleClick);

如果您通过通知发出行动号召,您还会希望定义可选的通知 id,这样您就可以确定用户选择了哪个行动号召。

图标

有关如何创建用于通知的图标的详细信息,请参阅 Acorn Design System 文档中的 图标设计

示例

GitHub 上的 webextensions-examples 存储库包括实现了通知的 notify-link-clicks-i18n 示例。