const CACHE_NAME = 'file-cache-v1' const FILE_TYPES = ['image/png', 'image/jpeg', 'image/gif', 'image/webp', 'image/svg+xml'] self.addEventListener('install', (event) => { console.log('Service Worker 安装') }) self.addEventListener('activate', (event) => { console.log('Service Worker 激活, 立即接管页面') event.waitUntil(clients.claim()) }) self.addEventListener('fetch', (event) => { //console.log('Service Worker 获取资源:', event.request.url) if (!event.request.url.match(/\.(jpeg|jpg|gif|png|webp|svg)$/i)) { return event.respondWith(fetch(event.request)) } event.respondWith( caches.match(event.request).then(async (cachedResponse) => { // 如果文件已缓存,则返回缓存的响应 if (cachedResponse) { console.log('使用了缓存:', event.request.url) for (const key of await caches.keys()) { const cache = await caches.open(key) const requests = await cache.keys() requests.forEach((request) => { console.log(request.url) }) } return cachedResponse } // 如果缓存中没有,则发起网络请求并缓存新图像(检查网络响应是否为文件) return fetch(event.request).then(async (networkResponse) => { if (networkResponse && networkResponse.ok && FILE_TYPES.includes(networkResponse.headers.get('Content-Type'))) { const cache = await caches.open(CACHE_NAME) await cache.put(event.request, networkResponse.clone()) } return networkResponse }) }) ) //// 先尝试从 webRTC 获取资源, 如果失败则从网络获取资源 //event.respondWith(async function () { // const response = await fetch(event.request) // return response //}()) //event.respondWith(fetch(event.request)) //self.clients.matchAll().then(clients => { // clients.forEach(client => { // client.postMessage('Hello from Service Worker') // }) //}) }) self.addEventListener('message', event => { console.log("%c收到主线程消息: " + event.data, 'color: red;') }) //// 检查通知权限 //if (Notification.permission === 'granted') { // // 如果已经授权,则可以显示通知 // registration.showNotification('Hello World') //} else if (Notification.permission === 'default') { // // 如果权限尚未授予,则请求权限 // Notification.requestPermission().then(permission => { // if (permission === 'granted') { // // 权限授予成功后显示通知 // showNotification(); // } else { // console.log('Notification permission denied'); // } // }).catch(err => { // console.log('Failed to request notification permission', err); // }); //} else { // console.log('Notification permission denied'); //}