使用 Notifications API

借助 browser.notifications API,您可以使用模板创建通知,并在用户的系统任务栏中向用户显示这些通知:

系统用户托盘中的通知

外观

富通知有四种不同的类型:基本、图片、列表和进度。所有通知都包含标题、消息、显示在通知消息左侧的小图标,以及 contextMessage 字段,该字段以较浅的颜色字体显示为第三个文本字段。

基本通知:

基本通知

列表通知可以显示任意数量的列表项:

列出通知

图片通知包含图片预览:

图片通知

进度通知会显示进度条:

进度通知

行为方式

在 ChromeOS 中,通知会显示在用户的系统任务栏中,并且会一直保留在系统任务栏中,直到用户将其关闭。系统任务栏会统计所有新通知的数量。用户在系统任务栏中看到通知后,计数会重置为零。

通知的优先级可以介于 -2 到 2 之间。优先级低于 0 的通知会显示在 ChromeOS 通知中心,但在其他平台上会产生错误。默认优先级为 0。优先级高于 0 时,显示时长会增加,并且系统任务栏中可以显示更多高优先级通知。

priority 设置不会影响 macOS 上通知的顺序。

除了显示信息之外,所有通知类型最多还可以包含两项操作项。当用户点击操作项时,扩展程序可以采取适当的操作进行响应。例如,当用户点击回复时,电子邮件应用会打开,用户可以完成回复:

通知中的操作

如何开发这些技能

如需使用此 API,请调用 notifications.create() 方法,并使用 options 参数传入通知详细信息:

await browser.notifications.create(id, options);

notifications.NotificationOptions 必须包含 notifications.TemplateType,用于定义可用的通知详细信息以及这些详细信息的显示方式。

创建基本通知

所有模板类型(basic、image、list 和 progress)都必须包含通知 title 和 message,以及 iconUrl(指向显示在通知消息左侧的小图标的链接)。

以下是 basic 模板的示例:

var opt = {
  type: "basic",
  title: "Primary Title",
  message: "Primary message to display",
  iconUrl: "url_to_small_icon"
}

使用图片

image 模板类型还包含 imageUrl,这是一个指向通知内预览的图片的链接。请注意,图片不会向 macOS 用户显示。

var opt = {
  type: "image",
  title: "Primary Title",
  message: "Primary message to display",
  iconUrl: "url_to_small_icon",
  imageUrl: "url_to_preview_image"
}

创建列表通知

list 模板以列表格式显示 items。请注意,在 macOS 上,系统只会向用户显示第一个项目。

var opt = {
  type: "list",
  title: "Primary Title",
  message: "Primary message to display",
  iconUrl: "url_to_small_icon",
  items: [{ title: "Item1", message: "This is item 1."},
          { title: "Item2", message: "This is item 2."},
          { title: "Item3", message: "This is item 3."}]
}```

### Create progress notification {: #progress }

The `progress` template displays a progress bar where current progress ranges from 0 to 100. On macOS the progress bar displays as a percentage value in the notification title instead of in the progress bar.

```js
var opt = {
  type: "progress",
  title: "Primary Title",
  message: "Primary message to display",
  iconUrl: "url_to_small_icon",
  progress: 42
}

监听和响应事件

所有通知都可以包含响应用户操作的事件监听器和事件处理脚本(请参阅 browser.events)。例如,您可以编写一个事件处理脚本来响应 notifications.onButtonClicked 事件。

事件监听器:

browser.notifications.onButtonClicked.addListener(replyBtnClick);

事件处理脚本:

function replyBtnClick {
    //Write function to respond to user action.
}

考虑在 Service Worker 中添加事件监听器和处理程序,以便即使扩展程序未运行,也能弹出通知。