问题描述
WorkBox 中的BackgroundSync 运行良好,但我遇到了问题
我希望当我修改一个元素时,即使请求仍在 indexedDB 中,当我离线时,该元素也不会在我的 pwa (UI) 上更新。 现在,当我更改元素(在一个简单的输入中)时,请求在我的 indexedDB 中,如果我刷新页面,它会像以前一样返回。当我再次拥有网络时,发送请求并在 UI 中更新元素
我将 workBox V6 用于我的工作服务,并使用 PHP API 来修改我的元素 这是我的 service worker 的同步部分:
你能帮我吗
解决方法
很难修改 workbox-background-sync
为您创建的 IndexedDB 条目以根据更新的参数调整排队的请求。
我建议改为直接删除您在 UI 中进行更改时知道已过期的 IndexedDB 条目,并在删除这些条目后,向您的服务器触发另一个 HTTP 请求。如果失败,具有更新值的最新请求将排队并在网络恢复后重试,而您的旧请求(您已从 IndexedDB 中删除)不会。
这样做不是很简单,但如果您需要,基本的想法是这样的:
// https://github.com/jakearchibald/idb for ease of use.
const {openDB} = await import('https://unpkg.com/[email protected]/build/esm/index.js?module');
const db = await openDB('workbox-background-sync');
const queuedRequests = await db.getAllFromIndex('requests','queueName');
for (const queuedRequest of queuedRequests) {
// Loop through queuedRequests until you find the one you want,// based on some criteria in shouldDelete().
if (shouldDelete(queuedRequests)) {
await db.delete('requests',queuedRequest.id);
}
}
请注意,此方法对 workbox-background-sync
将其请求序列化到 IndexedDB 的方式做出了一些假设,这些假设在 Workbox 的未来版本中可能并不总是适用。