javascript - React Service Worker:加载新内容而不强制用户关闭选项卡
问题描述
我正在努力在 react 中实现 service worker 概念,并且我已经添加了 Link making-a-progressive-web-app中建议的所有配置,但这里的问题是显示新内容(当网络从离线更改到在线),我必须向用户显示消息,例如“关闭现有选项卡后新内容可用。” 所以在这里我们强制用户关闭页面以显示新内容。即使是刷新选项也在这里不起作用。
检查以下方法 - (这是我们使用 create-react-app 构建 react 应用程序时创建的方法,该方法可以在 react-app/service-worker.js 中找到)
function registerValidSW(swUrl, config) {
navigator.serviceWorker
.register(swUrl)
.then(registration => {
registration.onupdatefound = () => {
const installingWorker = registration.installing;
if (installingWorker == null) {
return;
}
installingWorker.onstatechange = () => {
if (installingWorker.state === 'installed') {
if (navigator.serviceWorker.controller) {
// At this point, the updated precached content has been fetched,
// but the previous service worker will still serve the older
// content until all client tabs are closed.
console.log(
'New content is available and will be used when all ' +
'tabs for this page are closed. See'
);
// Execute callback
if (config && config.onUpdate) {
config.onUpdate(registration);
}
} else {
// At this point, everything has been precached.
// It's the perfect time to display a
// "Content is cached for offline use." message.
console.log('Content is cached for offline use.');
// Execute callback
if (config && config.onSuccess) {
config.onSuccess(registration);
}
}
}
};
};
})
.catch(error => {
console.error('Error during service worker registration:', error);
});
}
你可以清楚地看到控制台
新内容可用并将在此页面的所有选项卡关闭时使用。
实现这一目标的最佳方法是什么?所以只有刷新页面,我们才能更新之前存储的缓存。
解决方案
推荐阅读
- excel - 在字符串中包含一个单词并记录以下字符串
- c# - 如何修复 DeleteManyAsync 返回使用过滤器删除的 0 条记录?
- treeview - Vaadin 10 TreeGrid.refreshItem 仅在鼠标单击后刷新
- python - 当列表 1 中有匹配项时,如何检查两个不等长子列表的相似性并添加到列表 2 的分数?
- ajax - 使用post方法的Api.php中路由数据表的ajax问题
- json - Vue。Js Laravel 统计 JSON 的元素
- python - sklearn 中的 GridSearchCV 是否使用整个数据集训练模型?
- unit-testing - 编写混音单元测试时出错:URL 不可解析:remix_accounts.sol
- wordpress - 如何获取页面/帖子模板
- hibernate - 使用 Hibernate HQL 5 添加两个计数查询的结果