Javascript 如何在加载页面之前读取Client.postMessage?
我有一个服务工作者,当缓存资源发生更改时,它在获取期间发出Client.postMessage。我用它来通知用户他们可能需要刷新 我的问题是,当活动页面资源发生更改并且服务人员发出该消息时,该页面尚未加载,因此javascript无法接收该消息Javascript 如何在加载页面之前读取Client.postMessage?,javascript,service-worker,Javascript,Service Worker,我有一个服务工作者,当缓存资源发生更改时,它在获取期间发出Client.postMessage。我用它来通知用户他们可能需要刷新 我的问题是,当活动页面资源发生更改并且服务人员发出该消息时,该页面尚未加载,因此javascript无法接收该消息 有没有更好的方法来处理这种情况,而不是在发出消息之前使用waitUntil暂停几秒钟?另一种方法是从服务人员写入IndexedDB,然后在建立消息侦听器之前,在页面首次加载时读取它 为了简单起见,使用该库时可能会出现以下情况: // In your se
有没有更好的方法来处理这种情况,而不是在发出消息之前使用waitUntil暂停几秒钟?另一种方法是从服务人员写入IndexedDB,然后在建立
消息
侦听器之前,在页面首次加载时读取它
为了简单起见,使用该库时可能会出现以下情况:
// In your service worker:
importScripts('https://unpkg.com/idb-keyval@2.3.0/idb-keyval.js');
async function notifyOfUpdates(urls) {
const clients = await self.clients.matchAll();
for (const client of clients) {
client.postMessage({
// Structure your message however you'd like:
type: 'update',
urls,
});
}
// Read whatever's currently saved in IDB...
const updatedURLsInIDB = await idb.get('updated-urls') || [];
// ...append to the end of the list...
updatedURLsInIDB.push(...urls);
// ...and write the updated list to IDB.
await idb.set('updated-urls', updatedURLsInIDB);
}
// In your web page:
<script src="https://unpkg.com/idb-keyval@2.3.0/idb-keyval.js"></script>
<script>
async listenForUrlUpdates() {
const updatedURLsInIDB = await idb.get('updated-urls');
// Do something with updatedURLsInIDB...
// Clear out the list now that we've read it:
await idb.delete('updated-urls');
// Listen for ongoing updates:
navigator.serviceWorker.addEventListener('message', event => {
if (event.data.type === 'update') {
const updatedUrls = event.data.urls;
// Do something with updatedUrls
}
});
}
</script>
//在您的服务人员中:
进口文件('https://unpkg.com/idb-keyval@2.3.0/idb keyval.js');
异步函数notifyOfUpdates(URL){
const clients=等待self.clients.matchAll();
for(客户端的常量客户端){
client.postMessage({
//以您喜欢的方式组织您的邮件:
键入:“更新”,
网址,
});
}
//读取IDB中当前保存的内容。。。
const updatedURLsInIDB=wait idb.get('updated-url')| |[];
//…附加到列表的末尾。。。
updatedURLsInIDB.push(…URL);
//…并将更新后的列表写入IDB。
等待idb.set('updated-url',updatedURLsInIDB);
}
//在您的网页中:
异步listenForUrlUpdates(){
const updatedURLsInIDB=await idb.get('updated-url');
//使用updatedURLsInIDB执行某些操作。。。
//现在我们已经读过了,请清除列表:
等待idb.delete('updated-url');
//收听正在进行的更新:
navigator.serviceWorker.addEventListener('message',event=>{
如果(event.data.type==='update'){
const updatedUrls=event.data.url;
//用updatedUrls做点什么
}
});
}