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。