ServiceWorkerGlobalScope: backgroundfetchsuccess 事件
注意:此功能仅在 Service Workers 中可用。
ServiceWorkerGlobalScope 接口的 backgroundfetchsuccess 事件,在 后台获取 操作成功完成后触发:也就是说,当获取中的所有网络请求都成功完成后触发。
此事件不可取消,也不会冒泡。
语法
在诸如 addEventListener() 之类的方法中使用事件名称,或设置事件处理程序属性。
js
addEventListener("backgroundfetchsuccess", (event) => { })
onbackgroundfetchsuccess = (event) => { }
事件类型
事件属性
继承其父级 BackgroundFetchEvent 的属性。
BackgroundFetchUpdateUIEvent.updateUI()-
更新浏览器显示的用于展示获取操作进度的元素的 UI。
描述
当一个 后台获取 操作成功完成后(意味着所有单独的网络请求都已成功完成),浏览器会在必要时启动 service worker,并在 service worker 的全局作用域中触发 backgroundfetchsuccess 事件。
在此事件的处理程序中,service worker 可以检索并存储响应(例如,使用 Cache API)。要访问响应数据,service worker 使用事件的 registration 属性。
在后台获取 API 中,浏览器会向用户显示一个 UI 元素来指示操作的进度。在 backgroundfetchsuccess 处理程序中,service worker 可以更新该 UI 以显示操作已成功完成。为此,处理程序会调用事件的 updateUI() 方法,传入新的标题和/或图标。
示例
存储响应并更新 UI
此事件处理程序将所有响应存储在缓存中,并更新 UI。
js
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" });
});
});
规范
| 规范 |
|---|
| Background Fetch # dom-serviceworkerglobalscope-onbackgroundfetchsuccess |
浏览器兼容性
加载中…