93 lines
2.5 KiB
JavaScript
93 lines
2.5 KiB
JavaScript
// Service Worker版本,用于缓存更新
|
||
const CACHE_VERSION = 'v1';
|
||
const CACHE_NAME = `vip-video-cache-${CACHE_VERSION}`;
|
||
|
||
// 需要缓存的静态资源
|
||
const urlsToCache = [
|
||
'/',
|
||
'/index.html',
|
||
'/manifest.json',
|
||
'/icons/icon-192x192.png',
|
||
'/icons/icon-512x512.png'
|
||
];
|
||
|
||
// 安装Service Worker
|
||
self.addEventListener('install', (event) => {
|
||
event.waitUntil(
|
||
caches.open(CACHE_NAME)
|
||
.then((cache) => {
|
||
console.log('已打开缓存');
|
||
return cache.addAll(urlsToCache);
|
||
})
|
||
.then(() => self.skipWaiting())
|
||
);
|
||
});
|
||
|
||
// 激活Service Worker
|
||
self.addEventListener('activate', (event) => {
|
||
const cacheWhitelist = [CACHE_NAME];
|
||
|
||
event.waitUntil(
|
||
caches.keys().then((cacheNames) => {
|
||
return Promise.all(
|
||
cacheNames.map((cacheName) => {
|
||
if (cacheWhitelist.indexOf(cacheName) === -1) {
|
||
return caches.delete(cacheName);
|
||
}
|
||
})
|
||
);
|
||
}).then(() => self.clients.claim())
|
||
);
|
||
});
|
||
|
||
// 拦截网络请求
|
||
self.addEventListener('fetch', (event) => {
|
||
// 跳过非GET请求和非http/https请求
|
||
if (event.request.method !== 'GET' ||
|
||
!event.request.url.startsWith('http')) {
|
||
return;
|
||
}
|
||
|
||
// 跳过解析接口请求
|
||
if (event.request.url.includes('jx.xmflv.com') ||
|
||
event.request.url.includes('/api/')) {
|
||
return;
|
||
}
|
||
|
||
event.respondWith(
|
||
caches.match(event.request)
|
||
.then((response) => {
|
||
// 如果在缓存中找到响应,则返回缓存的响应
|
||
if (response) {
|
||
return response;
|
||
}
|
||
|
||
// 否则发起网络请求
|
||
return fetch(event.request).then(
|
||
(response) => {
|
||
// 检查是否收到有效的响应
|
||
if (!response || response.status !== 200 || response.type !== 'basic') {
|
||
return response;
|
||
}
|
||
|
||
// 克隆响应,因为响应是流,只能使用一次
|
||
const responseToCache = response.clone();
|
||
|
||
caches.open(CACHE_NAME)
|
||
.then((cache) => {
|
||
// 忽略查询参数的URL
|
||
const urlWithoutQuery = event.request.url.split('?')[0];
|
||
cache.put(event.request, responseToCache);
|
||
});
|
||
|
||
return response;
|
||
}
|
||
);
|
||
}).catch(() => {
|
||
// 如果请求失败且没有缓存,返回离线页面
|
||
if (event.request.mode === 'navigate') {
|
||
return caches.match('/');
|
||
}
|
||
})
|
||
);
|
||
});
|