我有一位服务生:
//IMPORT POLYFILL
importScripts('cache-polyfill.js');
//INSTALL
self.addEventListener('install', function(e) {
e.waitUntil(
caches.open('stock_item_balance_v1').then(function(cache) {
return cache.addAll([
'/app/offline_content/purchase/stock_items/stock_items_balance.php',
'/app/offline_content/purchase/stock_items/js/stock_items_balance.js'
]);
})
);
});
//FETCH (FETCH IS WHEN YOU CHECK FOR INTERNET)
self.addEventListener('fetch', function(event) {
//console.log(event.request.url);
event.respondWith(
caches.match(event.request).then(function(response) {
return response || fetch(event.request);
})
);
});在"stock_items_balance.php“中,我从DB中获取数据。因此,每隔30分钟,我想更新缓存的页面并重新加载窗口。
因此,首先,我有一个脚本,检查互联网连接。
如果为真,我希望清理/更新缓存并重新加载页面。
我怎么能这么做?
//INTERVAL
setInterval(function(){
//CLEAN/UPDATE CACHED FILES
serviceworker.update(); // ???
//RELOAD PAGE
window.location.reload();
}, 180000); 发布于 2021-03-16 13:29:29
(我想你有一个更大的问题,就是你描述的方法是否真的会给你的用户提供一个良好的、可预测的、离线的体验,但我只想关注你提出的实际技术问题。)
向服务人员发送消息
首先,您应该记住,对于同一个URL,有可能打开多个选项卡,如果您要运行更新代码,可能会多次运行。在异步缓存更新完成之后,此答案中的代码将从服务工作者内部为您处理“重新加载”步骤,方法是获取服务工作人员所有活动客户端的列表,并告诉每个客户端导航到当前URL (实际上是重新加载)。
// Additions to your service worker code:
self.addEventListener('message', (event) => {
// Optional: if you need to potentially send different
// messages, use a different identifier for each.
if (event.data === 'update') {
event.waitUntil((async () => {
// TODO: Move these URLs and cache names into constants.
const cache = await caches.open('stock_item_balance_v1');
await cache.addAll([
'/app/offline_content/purchase/stock_items/stock_items_balance.php',
'/app/offline_content/purchase/stock_items/js/stock_items_balance.js'
]);
const windowClients = await clients.matchAll();
for (const windowClient of windowClients) {
// Optional: check windowClient.url first and
// only call navigate() if it's the URL for one
// specific page.
windowClient.navigate(windowClient.url);
}
})());
}
});// Additions to your window/page code:
setInterval(() => {
if (navigator.serviceWorker.controller) {
navigator.serviceWorker.controller.postMessage('update');
}
}, 180000); 什么不起作用
缓存存储API可以在服务工作人员内部和页面的window范围内使用。通常,我建议大家从window上下文中打开相同的缓存,并调用cache.add(),用网络上的最新信息更新缓存条目。但是,从cache.add()上下文调用将导致网络请求被fetch处理程序拦截,此时,您的响应实际上不会来自网络。通过从服务工作人员内部调用cache.add(),您可以使生成的网络请求不会触发fetch处理程序。
https://stackoverflow.com/questions/66654292
复制相似问题