notifications.update()

更新给定 ID 的通知。

这是一个异步函数,返回一个 Promise

语法

js
let updating = browser.notifications.update(
  id,                            // string
  options                        // NotificationOptions
)

参数

id

string。要更新的通知的 ID。这与 notifications.create() 的回调中传入的 ID 相同。

options

notifications.NotificationOptions。定义通知的新内容和行为。

返回值

一个 Promise,它将以一个布尔值解析:如果通知已更新,则为 true;如果未更新(例如,因为引用的 id 不存在),则为 false

示例

此示例使用 update() 来更新进度通知。点击浏览器操作会显示通知并启动一个 alarm,我们用它来更新通知的进度指示器。

请注意,您需要“alarms” 权限 来创建警报(以及创建通知所需的“notifications”权限)。另请注意,Firefox 不支持 progress 属性。

js
let cakeNotification = "cake-notification";

/*

CAKE_INTERVAL is set to 0.3 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_PREP_INTERVAL = 0.005;

let progress = 0;

browser.alarms.onAlarm.addListener((alarm) => {
  progress += 10;
  if (progress > 100) {
    browser.notifications.clear(cakeNotification);
    browser.alarms.clear("cake-progress");
  } else {
    browser.notifications.update(cakeNotification, { progress });
  }
});

browser.browserAction.onClicked.addListener(() => {
  browser.notifications.getAll((all) => {
    if (all.length > 0) {
      browser.notifications.clear(cakeNotification);
      return;
    }
    progress = 0;
    browser.notifications.create(cakeNotification, {
      type: "progress",
      iconUrl: browser.extension.getURL("icons/cake-48.png"),
      title: "Your cake is being prepared…",
      message: "Something something cake",
      progress,
    });
    browser.alarms.create("cake-progress", {
      periodInMinutes: CAKE_PREP_INTERVAL,
    });
  });
});

浏览器兼容性

注意: 此 API 基于 Chromium 的 chrome.notifications API。