test: 强制更新: 清除缓存刷新

dev/timezone
Lei OT 2 years ago
parent 38866690c2
commit 83a7e93a2a

@ -449,3 +449,101 @@ export const sanitizeFilename = (str) => {
str = str.replace(/^-+|-+$/g, '');
return str;
}
export const formatBytes = (bytes, decimals = 2) => {
if (bytes === 0) return '';
const k = 1024;
const dm = decimals < 0 ? 0 : decimals;
const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
const i = Math.floor(Math.log(bytes) / Math.log(k));
return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + ' ' + sizes[i];
};
export const calcCacheSizes = async () => {
try {
let swCacheSize = 0;
let diskCacheSize = 0;
let indexedDBSize = 0;
// 1. Get the service worker cache size
if (navigator.serviceWorker) {
const cacheNames = await caches.keys();
for (const name of cacheNames) {
const cache = await caches.open(name);
const requests = await cache.keys();
for (const request of requests) {
const response = await cache.match(request);
swCacheSize += Number(response.headers.get('Content-Length')) || 0;
}
}
}
// 2. Get the disk cache size
const diskCacheName = 'disk-cache';
const diskCache = await caches.open(diskCacheName);
const diskCacheKeys = await diskCache.keys();
for (const request of diskCacheKeys) {
const response = await diskCache.match(request);
diskCacheSize += Number(response.headers.get('Content-Length')) || 0;
}
// 3. Get the IndexedDB cache size
// const indexedDBNames = await window.indexedDB.databases();
// for (const dbName of indexedDBNames) {
// const db = await window.indexedDB.open(dbName.name);
// const objectStoreNames = db.objectStoreNames;
// if (objectStoreNames !== undefined) {
// const objectStores = Array.from(objectStoreNames).map((storeName) => db.transaction([storeName], 'readonly').objectStore(storeName));
// for (const objectStore of objectStores) {
// const request = objectStore.count();
// request.onsuccess = () => {
// indexedDBSize += request.result;
// };
// }
// }
// }
return { swCacheSize, diskCacheSize, indexedDBSize, totalSize: Number(swCacheSize) + Number(diskCacheSize) + indexedDBSize };
} catch (error) {
console.error('Error getting cache sizes:', error);
}
};
export const clearAllCaches = async (cb) => {
try {
// 1. Clear the service worker cache
if (navigator.serviceWorker) {
const cacheNames = await caches.keys();
await Promise.all(cacheNames.map((name) => caches.delete(name)));
}
// 2. Clear the disk cache (HTTP cache)
const diskCacheName = 'disk-cache';
await window.caches.delete(diskCacheName);
const diskCache = await window.caches.open(diskCacheName);
const diskCacheKeys = await diskCache.keys();
await Promise.all(diskCacheKeys.map((request) => diskCache.delete(request)));
// 3. Clear the IndexedDB cache
const indexedDBNames = await window.indexedDB.databases();
await Promise.all(indexedDBNames.map((dbName) => window.indexedDB.deleteDatabase(dbName.name)));
// Unregister the service worker
const registration = await navigator.serviceWorker.getRegistration();
if (registration) {
await registration.unregister();
console.log('Service worker unregistered');
} else {
console.log('No service worker registered');
}
if (typeof cb === 'function' ) {
cb();
}
} catch (error) {
console.error('Error clearing caches or unregistering service worker:', error);
}
};

@ -1,117 +1,19 @@
import { createContext, useContext, useEffect, useState } from 'react';
import { App } from 'antd';
const formatBytes = (bytes, decimals = 2) => {
if (bytes === 0) return '';
const k = 1024;
const dm = decimals < 0 ? 0 : decimals;
const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
const i = Math.floor(Math.log(bytes) / Math.log(k));
return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + ' ' + sizes[i];
};
import { calcCacheSizes, clearAllCaches } from '@/utils/commons';
const ClearCache = (props) => {
const { message } = App.useApp();
const [cacheSizeInfo, setCacheSizeInfo] = useState({
swCacheSize: 0,
diskCacheSize: 0,
totalSize: 0,
});
useEffect(() => {
calcCacheSizes();
}, []);
const clearAllCaches = async () => {
try {
// 1. Clear the service worker cache
if (navigator.serviceWorker) {
const cacheNames = await caches.keys();
await Promise.all(cacheNames.map((name) => caches.delete(name)));
}
// 2. Clear the disk cache (HTTP cache)
const diskCacheName = 'disk-cache';
await window.caches.delete(diskCacheName);
const diskCache = await window.caches.open(diskCacheName);
const diskCacheKeys = await diskCache.keys();
await Promise.all(diskCacheKeys.map((request) => diskCache.delete(request)));
// 3. Clear the IndexedDB cache
const indexedDBNames = await window.indexedDB.databases();
await Promise.all(indexedDBNames.map((dbName) => window.indexedDB.deleteDatabase(dbName.name)));
// Unregister the service worker
const registration = await navigator.serviceWorker.getRegistration();
if (registration) {
await registration.unregister();
console.log('Service worker unregistered');
} else {
console.log('No service worker registered');
}
message.success(`清除成功🎉`);
// Display cache sizes
calcCacheSizes();
} catch (error) {
console.error('Error clearing caches or unregistering service worker:', error);
}
};
const calcCacheSizes = async () => {
try {
let swCacheSize = 0;
let diskCacheSize = 0;
let indexedDBSize = 0;
// 1. Get the service worker cache size
if (navigator.serviceWorker.controller) {
const cacheNames = await caches.keys();
for (const name of cacheNames) {
const cache = await caches.open(name);
const requests = await cache.keys();
for (const request of requests) {
const response = await cache.match(request);
swCacheSize += Number(response.headers.get('Content-Length')) || 0;
}
}
}
// 2. Get the disk cache size
const diskCacheName = 'disk-cache';
const diskCache = await caches.open(diskCacheName);
const diskCacheKeys = await diskCache.keys();
for (const request of diskCacheKeys) {
const response = await diskCache.match(request);
diskCacheSize += Number(response.headers.get('Content-Length')) || 0;
}
// 3. Get the IndexedDB cache size
// const indexedDBNames = await window.indexedDB.databases();
// for (const dbName of indexedDBNames) {
// const db = await window.indexedDB.open(dbName.name);
// const objectStoreNames = db.objectStoreNames;
// if (objectStoreNames !== undefined) {
// const objectStores = Array.from(objectStoreNames).map((storeName) => db.transaction([storeName], 'readonly').objectStore(storeName));
// for (const objectStore of objectStores) {
// const request = objectStore.count();
// request.onsuccess = () => {
// indexedDBSize += request.result;
// };
// }
// }
// }
setCacheSizeInfo({ swCacheSize, diskCacheSize, indexedDBSize, totalSize: Number(swCacheSize) + Number(diskCacheSize) + indexedDBSize });
} catch (error) {
console.error('Error getting cache sizes:', error);
}
};
// useEffect(() => {
// const cacheSizeInfo = calcCacheSizes();
// }, []);
const clearAllCachesA = async () => {
await clearAllCaches(message.success(`清除成功🎉`));
}
return (
<>
<a onClick={clearAllCaches}>
<a onClick={clearAllCachesA}>
清除缓存{/* &nbsp;{cacheSizeInfo.totalSize > 0 && <span>{formatBytes(cacheSizeInfo.totalSize)}</span>} */}
</a>
</>

@ -1,5 +1,6 @@
// import './ReloadPrompt.css';
import { clearAllCaches } from '@/utils/commons';
import { useRegisterSW } from 'virtual:pwa-register/react';
// import { pwaInfo } from 'virtual:pwa-info';
@ -45,6 +46,12 @@ function ReloadPrompt({ force }) {
setNeedRefresh(false);
};
const forceReload = async () => {
updateServiceWorker(true);
await clearAllCaches();
window.location.reload(true);
}
return (
<>
{/* {offlineReady && (<span>{APP_VERSION}</span>) } */}
@ -52,7 +59,7 @@ function ReloadPrompt({ force }) {
<a
className=' text-sky-600 pr-2'
onClick={() => {
needRefresh ? updateServiceWorker(true) : window.location.reload(true);
needRefresh ? updateServiceWorker(true) : forceReload()
}}>
系统更新{needRefresh && '🚀'}
</a>

Loading…
Cancel
Save