// 版本检查工具 export class VersionChecker { constructor() { this.currentVersion = import.meta.env.VITE_APP_VERSION || Date.now().toString() this.storageKey = 'h5_app_version' } // 检查版本更新 checkVersion() { const storedVersion = localStorage.getItem(this.storageKey) if (storedVersion !== this.currentVersion) { // 版本不匹配,清除缓存并刷新 this.clearCache() localStorage.setItem(this.storageKey, this.currentVersion) // 延迟刷新,确保缓存清理完成 setTimeout(() => { this.forceReload() }, 100) return true // 需要刷新 } return false // 不需要刷新 } // 清除应用缓存 clearCache() { // 清除localStorage(保留必要的数据) const keysToKeep = ['user_token', 'user_info'] // 保留的关键数据 const allKeys = Object.keys(localStorage) allKeys.forEach(key => { if (!keysToKeep.includes(key)) { localStorage.removeItem(key) } }) // 清除sessionStorage sessionStorage.clear() // 如果支持Service Worker,清除SW缓存 if ('serviceWorker' in navigator) { caches.keys().then(names => { names.forEach(name => { caches.delete(name) }) }) } } // 强制刷新页面 forceReload() { // 尝试硬刷新(清除缓存) if (window.location.reload) { window.location.reload(true) } else { // 备用方案:重新加载页面 window.location.href = window.location.href + '?t=' + Date.now() } } // 获取当前版本 getCurrentVersion() { return this.currentVersion } } // 导出单例 export const versionChecker = new VersionChecker()