tools/media-tools/video-parser/sw.js

93 lines
2.5 KiB
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// 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('/');
}
})
);
});