BackgroundFetchUpdateUIEvent

可用性有限

此特性不是基线特性,因为它在一些最广泛使用的浏览器中不起作用。

实验性: 这是一项实验性技术
在生产中使用此技术之前,请仔细检查浏览器兼容性表格

注意:此功能仅在 Service Workers 中可用。

BackgroundFetchUpdateUIEvent 接口是 Background Fetch API 的一个事件类型,用于 backgroundfetchsuccessbackgroundfetchfail 事件,并提供一个方法来更新应用的标题和图标,以便通知用户后台获取的成功或失败。

Event ExtendableEvent BackgroundFetchEvent BackgroundFetchUpdateUIEvent

构造函数

BackgroundFetchUpdateUIEvent() 实验性

创建一个新的 BackgroundFetchUIEvent 对象。这个构造函数通常不会被直接使用,因为浏览器会为 backgroundfetchsuccessbackgroundfetchfail 事件自行创建这些对象。

实例属性

还继承了其父接口 BackgroundFetchEvent 的属性。

实例方法

还继承了其父接口 BackgroundFetchEvent 的方法。

BackgroundFetchUpdateUIEvent.updateUI() 实验性

更新用户界面中的标题和图标,以显示后台获取的状态。返回一个 Promise

示例

在此示例中,会监听 backgroundfetchsuccess 事件,表明一个获取已成功完成。然后调用 updateUI() 方法,并附带一条消息,告知用户他们下载的剧集已准备就绪。

js
addEventListener("backgroundfetchsuccess", (event) => {
  const bgFetch = event.registration;

  event.waitUntil(
    (async () => {
      // Create/open a cache.
      const cache = await caches.open("downloads");
      // Get all the records.
      const records = await bgFetch.matchAll();
      // Copy each request/response across.
      const promises = records.map(async (record) => {
        const response = await record.responseReady;
        await cache.put(record.request, response);
      });

      // Wait for the copying to complete.
      await Promise.all(promises);

      // Update the progress notification.
      event.updateUI({ title: "Episode 5 ready to listen!" });
    })(),
  );
});

规范

规范
Background Fetch
# background-fetch-update-ui-event

浏览器兼容性