notifications.create()
创建并显示一个通知。
传递一个 notifications.NotificationOptions
对象来定义通知的内容和行为。
您可以选择性地为通知提供一个 ID。如果省略 ID,系统将生成一个 ID。您可以使用该 ID 来 update
或 clear
该通知。
这是一个异步函数,返回一个 Promise
。
警告: 如果您在短时间内连续多次调用 notifications.create()
,Firefox 可能会导致不显示任何通知。
语法
js
let creating = browser.notifications.create(
id, // optional string
options // NotificationOptions
)
参数
id
可选-
string
。此 ID 用于在notifications.update()
、notifications.clear()
以及事件监听器中引用此通知。如果您省略此参数或传递一个空字符串,则会为此通知生成一个新的 ID。如果您提供的 ID 与此扩展中现有通知的 ID 匹配,则会清除旧通知。 options
-
notifications.NotificationOptions
。定义通知的内容和行为。
返回值
一个 Promise
,当通知创建并开始显示过程(早于用户实际看到通知之前)时,该 Promise 将被 fulfilled。它将以一个表示通知 ID 的字符串 fulfilled。
示例
此示例使用 alarm
定期显示一个通知。点击浏览器操作会关闭通知。您需要“alarms” 权限 来创建闹钟(以及“notifications”权限来创建通知)。
js
let cakeNotification = "cake-notification";
/*
CAKE_INTERVAL is set to 6 seconds in this example.
Such a short period is chosen to make the extension's behavior
more obvious, but this is not recommended in real life.
Note that in Chrome, alarms cannot be set for less
than a minute.
*/
let CAKE_INTERVAL = 0.1;
browser.alarms.create("", { periodInMinutes: CAKE_INTERVAL });
browser.alarms.onAlarm.addListener((alarm) => {
browser.notifications.create(cakeNotification, {
type: "basic",
iconUrl: browser.runtime.getURL("icons/cake-96.png"),
title: "Time for cake!",
message: "Something something cake",
});
});
browser.browserAction.onClicked.addListener(() => {
const clearing = browser.notifications.clear(cakeNotification);
clearing.then(() => {
console.log("cleared");
});
});
扩展程序示例
浏览器兼容性
加载中…
注意: 此 API 基于 Chromium 的 chrome.notifications
API。