1- const CACHE_NAME = 'epub-browser-v5 ' ;
1+ const CACHE_NAME = 'epub-browser-v7 ' ;
22
33const STATIC_ASSETS = [
44 '/' ,
@@ -51,7 +51,22 @@ self.addEventListener('activate', (event) => {
5151 self . clients . claim ( ) ;
5252} ) ;
5353
54- // 判断是否应该缓存该请求(只缓存静态资源)
54+ // 监听消息(清除缓存)
55+ self . addEventListener ( 'message' , ( event ) => {
56+ if ( event . data && event . data . action === 'CLEAR_CACHE' ) {
57+ event . waitUntil (
58+ caches . delete ( CACHE_NAME ) . then ( ( ) => {
59+ console . log ( 'Cache cleared:' , CACHE_NAME ) ;
60+ // 重新预缓存静态资源
61+ return caches . open ( CACHE_NAME ) . then ( ( cache ) => {
62+ return cache . addAll ( STATIC_ASSETS ) ;
63+ } ) ;
64+ } )
65+ ) ;
66+ }
67+ } ) ;
68+
69+ // 判断是否应该缓存该请求
5570function shouldCache ( url ) {
5671 const urlObj = new URL ( url ) ;
5772 const pathname = urlObj . pathname ;
@@ -61,7 +76,12 @@ function shouldCache(url) {
6176 return true ;
6277 }
6378
64- // 只缓存根页面
79+ // 缓存书籍页面
80+ if ( pathname . startsWith ( '/book/' ) ) {
81+ return true ;
82+ }
83+
84+ // 缓存根页面
6585 if ( pathname === '/' || pathname === '/index.html' ) {
6686 return true ;
6787 }
@@ -81,8 +101,29 @@ self.addEventListener('fetch', (event) => {
81101 return ;
82102 }
83103
84- // 导航请求 (页面跳转)- 直接从网络获取,不经过 Service Worker
104+ // 对于导航请求 (页面跳转),使用网络优先策略
85105 if ( event . request . mode === 'navigate' ) {
106+ event . respondWith (
107+ fetch ( event . request )
108+ . then ( ( response ) => {
109+ // 缓存响应
110+ if ( response && response . status === 200 ) {
111+ const responseToCache = response . clone ( ) ;
112+ caches . open ( CACHE_NAME )
113+ . then ( ( cache ) => {
114+ cache . put ( event . request , responseToCache ) ;
115+ } ) ;
116+ }
117+ return response ;
118+ } )
119+ . catch ( ( ) => {
120+ // 网络失败时,返回缓存
121+ return caches . match ( event . request )
122+ . then ( ( cachedResponse ) => {
123+ return cachedResponse || caches . match ( '/index.html' ) ;
124+ } ) ;
125+ } )
126+ ) ;
86127 return ;
87128 }
88129
@@ -115,9 +156,9 @@ self.addEventListener('fetch', (event) => {
115156 return response ;
116157 } )
117158 . catch ( ( ) => {
118- // 如果网络请求失败,返回备用响应
119- if ( event . request . destination === 'image ' ) {
120- return new Response ( '' , { status : 404 } ) ;
159+ // 如果网络请求失败,尝试返回缓存的首页
160+ if ( event . request . destination === 'document ' ) {
161+ return caches . match ( '/index.html' ) ;
121162 }
122163 } ) ;
123164 } )
0 commit comments