借助 chrome.notifications
API,您可以使用模板创建通知,并在用户的系统任务栏中向用户显示这些通知:
外观
内容丰富的通知有四种不同的版本:基本通知、图片通知、列表通知和进度通知。所有通知均包括标题、消息、通知消息左侧显示的小图标,以及以浅色字体显示的 contextMessage
字段(显示为第三个文本字段)。
基本通知:
列表通知会显示任意数量的列表项:
图片通知包含图片预览:
进度通知会显示进度条:
行为方式
在 ChromeOS 上,通知会显示在用户的系统任务栏中,并会一直保留在系统任务栏中,直到用户将其关闭。系统任务栏保留所有新通知的计数。用户在系统任务栏中看到这些通知后,计数就会重置为零。
您可为通知分配 -2 到 2 之间的优先级。小于 0 的优先级会显示在 ChromeOS 通知中心,并且会在其他平台上产生错误。默认优先级为 0。 优先级大于 0 的通知会随着时长增加而显示,并且系统任务栏中可显示更多高优先级通知。
priority
设置不会影响 macOS 上的通知顺序。
除了显示信息之外,所有通知类型最多还可以包含两个操作项。当用户点击某个操作项时,您的扩展程序可以做出适当的响应。例如,当用户点击回复时,系统会打开电子邮件应用,并且用户可以完成回复:
制作方法
如需使用此 API,请调用 notifications.create()
方法,并使用 options
参数传入通知详细信息:
await chrome.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
}
监听和响应事件
所有通知都可以包含响应用户操作的事件监听器和事件处理脚本(请参阅 chrome.events
)。例如,您可以编写事件处理脚本来响应 notifications.onButtonClicked
事件。
事件监听器:
chrome.notifications.onButtonClicked.addListener(replyBtnClick);
事件处理脚本:
function replyBtnClick {
//Write function to respond to user action.
}
考虑在 Service Worker 中添加事件监听器和处理程序,以便即使扩展程序未运行,通知也能弹出。