-
Notifications
You must be signed in to change notification settings - Fork 7
Open
Description
问题描述:
如题。
我目前采用 postMessage 方式,将命中信息传递给主进程,在主进程进行上报统计。不过,有个问题是在主进程,并有时并未监听接收到消息
下面是我的缓存命中统计的埋点,下面代码所注
sw-register.js
navigator.serviceWorker.addEventListener('message', function (e) {
console.log('postMessage数据', e.data)
if (e.data.type === 'update') {
console.log('重新加载页面', e.data)
location.reload()
}
if (e.data.type === 'cache') {
console.log('命中缓存', e.data)
}
if (e.data.type === 'uncache') {
console.log('缓存未命中', e.data)
}
})sw.js
self.addEventListener('fetch', function (evt) {
// ...
evt.respondWith(
caches.match(evt.request).then(async function (response) {
if (response) {
clients.forEach(client => {
///////////////////////->命中缓存<-////////////////////////////
// client.postMessage({ type: 'cache', msg: requestStr })
})
return response
}
return fetch(evt.request).then(function (response) {
let cpResponse = response.clone()
// console.log('fetch获取到的response:', response)
caches.open(version).then(function (cache) {
cache.put(evt.request, cpResponse)
clients.forEach(client => {
///////////////////////->未命中缓存<-//////////////////////////
client.postMessage({ type: 'uncache', msg: requestStr })
})
})
return response
})
}).catch(function (err) {
console.error('fetch 接口错误', err)
throw err
})
)
})请问:
1.为何使用 postMessage 方式,无法监听接收到消息?
2.ServiceWorker缓存成功后,有没有更好的方法进行上报量化统计?
Reactions are currently unavailable
Metadata
Metadata
Assignees
Labels
No labels