@@ -2,30 +2,48 @@ import { useRegisterSW } from 'virtual:pwa-register/vue'
2
2
3
3
export default defineNuxtPlugin ( ( ) => {
4
4
const online = useOnline ( )
5
+ const registrationError = ref ( false )
6
+ const swActivated = ref ( false )
7
+
8
+ const registerPeriodicSync = ( swUrl : string , r : ServiceWorkerRegistration ) => {
9
+ setInterval ( async ( ) => {
10
+ if ( ! online . value )
11
+ return
12
+
13
+ const resp = await fetch ( swUrl , {
14
+ cache : 'no-store' ,
15
+ headers : {
16
+ 'cache' : 'no-store' ,
17
+ 'cache-control' : 'no-cache' ,
18
+ } ,
19
+ } )
20
+
21
+ if ( resp ?. status === 200 )
22
+ await r . update ( )
23
+ } , 60 * 60 * 1000 /* 1 hour */ )
24
+ }
5
25
6
26
const {
7
27
needRefresh, updateServiceWorker,
8
28
} = useRegisterSW ( {
9
29
immediate : true ,
30
+ onRegisterError ( ) {
31
+ registrationError . value = true
32
+ } ,
10
33
onRegisteredSW ( swUrl , r ) {
11
- if ( ! r || r . installing )
12
- return
13
-
14
- setInterval ( async ( ) => {
15
- if ( ! online . value )
16
- return
17
-
18
- const resp = await fetch ( swUrl , {
19
- cache : 'no-store' ,
20
- headers : {
21
- 'cache' : 'no-store' ,
22
- 'cache-control' : 'no-cache' ,
23
- } ,
34
+ // should add support in pwa plugin
35
+ if ( r ?. active ?. state === 'activated' ) {
36
+ swActivated . value = true
37
+ registerPeriodicSync ( swUrl , r )
38
+ }
39
+ else if ( r ?. installing ) {
40
+ r . installing . addEventListener ( 'statechange' , ( e ) => {
41
+ const sw = e . target as ServiceWorker
42
+ swActivated . value = sw . state === 'activated'
43
+ if ( swActivated . value )
44
+ registerPeriodicSync ( swUrl , r )
24
45
} )
25
-
26
- if ( resp ?. status === 200 )
27
- await r . update ( )
28
- } , 60 * 60 * 1000 /* 1 hour */ )
46
+ }
29
47
} ,
30
48
} )
31
49
@@ -36,6 +54,8 @@ export default defineNuxtPlugin(() => {
36
54
return {
37
55
provide : {
38
56
pwa : reactive ( {
57
+ swActivated,
58
+ registrationError,
39
59
needRefresh,
40
60
updateServiceWorker,
41
61
close,
0 commit comments