大网数据广告活动
Web 标准与前端开发

ServiceWorkerGlobalScope: backgroundfetchsuccess event

· 52CE 我爱测

The **`backgroundfetchsuccess`** event of the ServiceWorkerGlobalScope interface is fired when a background fetch operation has completed successfully: that is, when all network requests in the fetch have completed successfully.

Background Fetch APIservice

The backgroundfetchsuccess event of the ServiceWorkerGlobalScope interface is fired when a background fetch operation has completed successfully: that is, when all network requests in the fetch have completed successfully.

This event is not cancelable and does not bubble.

Syntax

Use the event name in EventTarget/addEventListener:

addEventListener("backgroundfetchsuccess", (event) => { })

Alternatively, assign to the event handler property of the interface:

onbackgroundfetchsuccess = (event) => { }

Event type

A BackgroundFetchUpdateUIEvent.

BackgroundFetchUpdateUIEvent

Description

When a background fetch operation completes successfully (meaning that all individual network requests have completed successfully), the browser starts the service worker, if necessary, and fires the backgroundfetchsuccess event in the service worker's global scope.

In the handler for this event, the service worker can retrieve and store the responses (for example, using the Cache API). To access the response data, the service worker uses the event's BackgroundFetchEvent/registration property.

In the background fetch API, the browser shows a UI element to the user to indicate the progress of the operation. In the backgroundfetchsuccess handler, the service worker can update that UI to show that the operation has completed successfully. To do this, the handler calls the event's BackgroundFetchUpdateUIEvent/updateUI method, passing in a new title and/or icons.

Examples

Storing responses and updating UI

This event handler stores all responses in the cache, and updates the UI.

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

  event.waitUntil(async () => {
    // Open a cache
    const cache = await caches.open("movies");
    // Get all the records
    const records = await registration.matchAll();
    // Cache all responses
    const cachePromises = records.map(async (record) => {
      const response = await record.responseReady;
      await cache.put(record.request, response);
    });

    // Wait for caching to finish
    await Promise.all(cachePromises);

    // Update the browser's UI
    event.updateUI({ title: "Move download complete" });
  });
});

Specifications

Browser compatibility

See also

来源:MDN Web Docs / Mozilla 贡献者 · 作者与贡献记录 · CC BY-SA 2.5。离线整理了版式、链接和媒体显示。

资料来源与适用范围

资料来源
MDN Web Docs / Mozilla 贡献者
适用范围
请按文中版本与环境说明核对
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-15
授权说明
CC BY-SA 2.5

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。