本地缓存文件

This commit is contained in:
SunWuyuan
2025-04-05 09:23:27 +08:00
parent 291c593178
commit 8a1e44f1fa
15 changed files with 612 additions and 49 deletions
+238
View File
@@ -0,0 +1,238 @@
<template>
<v-card>
<v-card-title class="d-flex align-center">
<span>缓存管理</span>
<v-spacer></v-spacer>
<v-btn color="error" @click="clearAllCaches" :loading="loading">
清除所有缓存
</v-btn>
<v-btn icon class="ml-2" @click="refreshCaches">
<v-icon>mdi-refresh</v-icon>
</v-btn>
</v-card-title>
<v-card-text>
<v-alert v-if="!serviceWorkerActive" type="warning" class="mb-4">
Service Worker 未激活,缓存管理功能不可用。
</v-alert>
<v-alert v-if="message" :type="messageType" class="mb-4">
{{ message }}
</v-alert>
<v-expansion-panels v-if="caches.length > 0">
<v-expansion-panel v-for="cache in caches" :key="cache.name">
<v-expansion-panel-title>
<div class="d-flex align-center">
<span>{{ formatCacheName(cache.name) }}</span>
<v-chip class="ml-2" size="small">{{ cache.urls.length }} 个文件</v-chip>
</div>
</v-expansion-panel-title>
<v-expansion-panel-text>
<div class="d-flex justify-end mb-2">
<v-btn color="error" size="small" @click="clearCache(cache.name)" :loading="loading">
清除此缓存
</v-btn>
</div>
<v-list lines="two">
<v-list-item v-for="(url, index) in cache.urls" :key="index">
<v-list-item-title class="text-truncate">
{{ getFileName(url) }}
</v-list-item-title>
<v-list-item-subtitle class="text-truncate">
{{ url }}
</v-list-item-subtitle>
<template v-slot:append>
<v-btn icon size="small" color="error" @click="clearUrl(cache.name, url)">
<v-icon>mdi-delete</v-icon>
</v-btn>
</template>
</v-list-item>
</v-list>
</v-expansion-panel-text>
</v-expansion-panel>
</v-expansion-panels>
<v-skeleton-loader v-else-if="loading" type="article" />
<v-alert v-else type="info">
没有找到缓存数据。
</v-alert>
</v-card-text>
</v-card>
</template>
<script>
export default {
name: 'CacheManager',
data() {
return {
caches: [],
loading: false,
serviceWorkerActive: false,
message: '',
messageType: 'info',
}
},
mounted() {
this.checkServiceWorker();
},
methods: {
checkServiceWorker() {
if ('serviceWorker' in navigator) {
navigator.serviceWorker.ready.then(() => {
this.serviceWorkerActive = true;
this.refreshCaches();
}).catch(() => {
this.serviceWorkerActive = false;
});
} else {
this.serviceWorkerActive = false;
}
},
async refreshCaches() {
if (!this.serviceWorkerActive) return;
this.loading = true;
this.message = '';
this.caches = [];
try {
// 获取所有缓存名称
const cacheNames = await this.sendMessageToSW({ type: 'CACHE_KEYS' });
// 获取每个缓存的内容
for (const cacheName of cacheNames.cacheNames) {
const cacheContent = await this.sendMessageToSW({
type: 'CACHE_CONTENT',
cacheName
});
this.caches.push({
name: cacheName,
urls: cacheContent.urls || []
});
}
} catch (error) {
this.showMessage('获取缓存信息失败: ' + error.message, 'error');
} finally {
this.loading = false;
}
},
async clearCache(cacheName) {
this.loading = true;
try {
const result = await this.sendMessageToSW({
type: 'CLEAR_CACHE',
cacheName
});
if (result.success) {
this.showMessage(`已清除缓存: ${this.formatCacheName(cacheName)}`, 'success');
await this.refreshCaches();
} else {
this.showMessage('清除缓存失败', 'error');
}
} catch (error) {
this.showMessage('清除缓存失败: ' + error.message, 'error');
} finally {
this.loading = false;
}
},
async clearUrl(cacheName, url) {
this.loading = true;
try {
const result = await this.sendMessageToSW({
type: 'CLEAR_URL',
cacheName,
url
});
if (result.success) {
this.showMessage(`已从缓存中删除: ${this.getFileName(url)}`, 'success');
await this.refreshCaches();
} else {
this.showMessage('删除缓存项失败', 'error');
}
} catch (error) {
this.showMessage('删除缓存项失败: ' + error.message, 'error');
} finally {
this.loading = false;
}
},
async clearAllCaches() {
if (!confirm('确定要清除所有缓存吗?这可能会导致应用需要重新下载资源。')) {
return;
}
this.loading = true;
try {
const result = await this.sendMessageToSW({ type: 'CLEAR_ALL_CACHES' });
if (result.success) {
this.showMessage('已清除所有缓存', 'success');
await this.refreshCaches();
} else {
this.showMessage('清除所有缓存失败', 'error');
}
} catch (error) {
this.showMessage('清除所有缓存失败: ' + error.message, 'error');
} finally {
this.loading = false;
}
},
sendMessageToSW(message) {
return new Promise((resolve, reject) => {
if (!navigator.serviceWorker.controller) {
reject(new Error('Service Worker 未控制页面'));
return;
}
const messageChannel = new MessageChannel();
messageChannel.port1.onmessage = (event) => {
resolve(event.data);
};
navigator.serviceWorker.controller.postMessage(message, [messageChannel.port2]);
// 设置超时
setTimeout(() => {
reject(new Error('Service Worker 响应超时'));
}, 5000);
});
},
formatCacheName(name) {
// 格式化缓存名称,使其更易读
return name
.replace('workbox-precache-', '预缓存-')
.replace('-cache', '')
.replace('js', 'JS')
.replace('css', 'CSS')
.replace('html', 'HTML')
.replace('images', '图片')
.replace('external-resources', '外部资源')
.replace('cdn-cgi', 'CDN');
},
getFileName(url) {
try {
const urlObj = new URL(url);
const pathParts = urlObj.pathname.split('/');
return pathParts[pathParts.length - 1] || urlObj.hostname;
} catch (e) {
return url;
}
},
showMessage(message, type = 'info') {
this.message = message;
this.messageType = type;
// 5秒后自动清除消息
setTimeout(() => {
if (this.message === message) {
this.message = '';
}
}, 5000);
}
}
}
</script>
@@ -9,11 +9,7 @@
</template>
<v-list-item-title>检查服务器连接</v-list-item-title>
<template #append>
<v-btn
:loading="loading"
variant="tonal"
@click="checkServerConnection"
>
<v-btn :loading="loading" variant="tonal" @click="checkServerConnection">
测试连接
</v-btn>
</template>
@@ -27,9 +23,7 @@
<v-icon icon="mdi-database" class="mr-3" />
</template>
<v-list-item-title>清除数据库缓存</v-list-item-title>
<v-list-item-subtitle
>这将清除所有IndexedDB中的数据</v-list-item-subtitle
>
<v-list-item-subtitle>这将清除所有IndexedDB中的数据</v-list-item-subtitle>
<template #append>
<v-btn color="error" variant="tonal" @click="confirmClearIndexedDB">
清除
@@ -46,6 +40,17 @@
</template>
</v-list-item>
</template>
<v-list-item>
<template #prepend>
<v-icon icon="mdi-lan-connect" class="mr-3" />
</template>
<v-list-item-title>查看本地缓存</v-list-item-title>
<template #append>
<v-btn variant="tonal" to="/cachemanagement">
查看
</v-btn>
</template>
</v-list-item>
</v-list>
<!-- 确认对话框 -->
@@ -55,12 +60,8 @@
<v-card-text>{{ confirmMessage }}</v-card-text>
<v-card-actions>
<v-spacer></v-spacer>
<v-btn color="grey" variant="text" @click="confirmDialog = false"
>取消</v-btn
>
<v-btn color="error" variant="tonal" @click="handleConfirm"
>确认</v-btn
>
<v-btn color="grey" variant="text" @click="confirmDialog = false">取消</v-btn>
<v-btn color="error" variant="tonal" @click="handleConfirm">确认</v-btn>
</v-card-actions>
</v-card>
</v-dialog>
+22
View File
@@ -0,0 +1,22 @@
<template>
<v-container>
<v-row>
<v-col cols="12">
<h1 class="text-h4 mb-4">缓存管理</h1>
<p class="mb-6">在这里您可以查看和管理应用的缓存文件。清除缓存可能会导致应用需要重新下载资源。</p>
<CacheManager />
</v-col>
</v-row>
</v-container>
</template>
<script>
import CacheManager from '@/components/CacheManager.vue';
export default {
name: 'CacheManagementPage',
components: {
CacheManager
}
}
</script>
+141
View File
@@ -0,0 +1,141 @@
import { precacheAndRoute, cleanupOutdatedCaches } from 'workbox-precaching'
import { registerRoute, setCatchHandler } from 'workbox-routing'
import { CacheFirst, NetworkFirst, StaleWhileRevalidate } from 'workbox-strategies'
import { ExpirationPlugin } from 'workbox-expiration'
import { CacheableResponsePlugin } from 'workbox-cacheable-response'
// 使用 self.__WB_MANIFEST 是 workbox 的一个特殊变量,会被实际的预缓存清单替换
precacheAndRoute(self.__WB_MANIFEST)
cleanupOutdatedCaches()
// JS 文件缓存
registerRoute(
/\.(?:js)$/i,
new StaleWhileRevalidate({
cacheName: 'js-cache',
plugins: [
new ExpirationPlugin({
maxEntries: 100,
maxAgeSeconds: 60 * 60 * 24 * 7 // 7 天
})
]
})
)
// CSS 文件缓存
registerRoute(
/\.(?:css)$/i,
new StaleWhileRevalidate({
cacheName: 'css-cache',
plugins: [
new ExpirationPlugin({
maxEntries: 50,
maxAgeSeconds: 60 * 60 * 24 * 7 // 7 天
})
]
})
)
// HTML 文件缓存
registerRoute(
/\.(?:html)$/i,
new NetworkFirst({
cacheName: 'html-cache',
plugins: [
new ExpirationPlugin({
maxEntries: 20,
maxAgeSeconds: 60 * 60 * 24 // 1 天
})
]
})
)
// 图片缓存
registerRoute(
/\.(?:png|jpg|jpeg|svg|gif)$/i,
new StaleWhileRevalidate({
cacheName: 'images-cache',
plugins: [
new ExpirationPlugin({
maxEntries: 50,
maxAgeSeconds: 60 * 60 * 24 * 30 // 30 天
})
]
})
)
// CDN 缓存
registerRoute(
/\/cdn-cgi\/.*/i,
new NetworkFirst({
cacheName: 'cdn-cgi-cache',
plugins: [
new ExpirationPlugin({
maxEntries: 50,
maxAgeSeconds: 60 * 60 * 24 // 1 天
})
],
networkTimeoutSeconds: 10
})
)
// 外部资源缓存
registerRoute(
({ url }) => url.origin !== self.location.origin,
new NetworkFirst({
cacheName: 'external-resources',
plugins: [
new ExpirationPlugin({
maxEntries: 100,
maxAgeSeconds: 60 * 60 * 24 // 1 天
}),
new CacheableResponsePlugin({
statuses: [0, 200]
})
],
networkTimeoutSeconds: 10
})
)
// 添加缓存管理消息处理
self.addEventListener('message', (event) => {
if (event.data && event.data.type === 'CACHE_KEYS') {
// 获取所有缓存键
caches.keys().then((cacheNames) => {
event.ports[0].postMessage({ cacheNames });
});
} else if (event.data && event.data.type === 'CACHE_CONTENT') {
// 获取特定缓存的内容
const cacheName = event.data.cacheName;
caches.open(cacheName).then((cache) => {
cache.keys().then((requests) => {
const urls = requests.map(request => request.url);
event.ports[0].postMessage({ cacheName, urls });
});
});
} else if (event.data && event.data.type === 'CLEAR_CACHE') {
// 清除特定缓存
const cacheName = event.data.cacheName;
caches.delete(cacheName).then((success) => {
event.ports[0].postMessage({ success, cacheName });
});
} else if (event.data && event.data.type === 'CLEAR_URL') {
// 清除特定URL的缓存
const cacheName = event.data.cacheName;
const url = event.data.url;
caches.open(cacheName).then((cache) => {
cache.delete(url).then((success) => {
event.ports[0].postMessage({ success, cacheName, url });
});
});
} else if (event.data && event.data.type === 'CLEAR_ALL_CACHES') {
// 清除所有缓存
caches.keys().then((cacheNames) => {
Promise.all(
cacheNames.map(name => caches.delete(name))
).then(() => {
event.ports[0].postMessage({ success: true });
});
});
}
});