热门问题如何卸载 Service Worker?对于使用 JavaScript 注销服务工作者有一个很好的答案。如何让服务工作线程在取消注册时清除所有命名缓存?
从 MDN 来看unregister,Service Worker 将在取消注册之前完成任何正在进行的操作。所以,听起来应该可以监听一个uninstall事件,但据我所知,不存在这样的事件。为了咯咯笑,我尝试添加self.addEventListener('uninstall', ...)到服务工作者中,但正如预期的那样,它在取消注册时没有触发。我还尝试监听任何message可能在取消注册时发送的内容...没有骰子。
我还考虑过观察Service Worker stateinstalling ,但、installed、activating、activated和似乎都不redundant相关。更不用说,看起来不可能将消息传递给服务工作线程,所以我不确定我会如何处理uninstalling来自服务工作线程外部的状态。
伸手去拿吸管,虽然我看到了对卸载标志的引用,但我没有看到它暴露在任何地方。建议?
以下代码应取消注册所有服务工作线程并清除源的缓存存储 API 中的所有内容:
async function unregisterAndClearCaches() {
const registrations = await navigator.serviceWorker.getRegistrations();
const unregisterPromises = registrations.map(registration => registration.unregister());
const allCaches = await caches.keys();
const cacheDeletionPromises = allCaches.map(cache => caches.delete(cache));
await Promise.all([...unregisterPromises, ...cacheDeletionPromises]);
}
Run Code Online (Sandbox Code Playgroud)
使用Clear-Site-Data标头是在单个操作中“强制”清除所有内容(服务工作线程注册、缓存等)的另一种选择。
| 归档时间: |
|
| 查看次数: |
2427 次 |
| 最近记录: |