0
# Service Worker Events
1
2
Client-side service worker event handling and update management for PWA functionality, including event bus communication and update activation.
3
4
## Capabilities
5
6
### SWUpdateEvent Class
7
8
Event wrapper for service worker registration updates that provides methods for checking updates and activating new service workers.
9
10
```javascript { .api }
11
/**
12
* Service worker update event wrapper
13
* @param {ServiceWorkerRegistration} registration - Service worker registration object
14
*/
15
class SWUpdateEvent {
16
constructor(registration: ServiceWorkerRegistration);
17
18
/** Service worker registration instance */
19
readonly registration: ServiceWorkerRegistration;
20
21
/**
22
* Check if the new service worker exists or not
23
* @returns {Promise<ServiceWorkerRegistration>} Promise resolving to updated registration
24
*/
25
update(): Promise<ServiceWorkerRegistration>;
26
27
/**
28
* Activate new service worker to work with new data
29
* Triggers skipWaiting() on the waiting service worker
30
* @returns {Promise<any>} Promise resolving when skip waiting is complete
31
*/
32
skipWaiting(): Promise<any>;
33
}
34
```
35
36
**Usage Examples:**
37
38
```javascript
39
import event from '@sw-event';
40
41
// Listen for service worker updates
42
event.$on('sw-updated', (updateEvent) => {
43
console.log('New service worker available');
44
45
// Check for updates
46
updateEvent.update().then(() => {
47
console.log('Update check completed');
48
});
49
50
// Activate new service worker immediately
51
updateEvent.skipWaiting().then(() => {
52
// Reload page to use new service worker
53
location.reload(true);
54
});
55
});
56
```
57
58
### Service Worker Event Bus
59
60
Global Vue event bus for managing service worker lifecycle events and communication between components.
61
62
```javascript { .api }
63
/**
64
* Global event bus for service worker events
65
* Exported from '@sw-event' alias
66
*/
67
const swEventBus: Vue;
68
```
69
70
**Available Events:**
71
72
```javascript { .api }
73
interface ServiceWorkerEvents {
74
/** Service worker is active and ready */
75
'sw-ready': () => void;
76
77
/** Content has been cached for offline use */
78
'sw-cached': (event: SWUpdateEvent) => void;
79
80
/** New content is available for update */
81
'sw-updated': (event: SWUpdateEvent) => void;
82
83
/** App is running in offline mode */
84
'sw-offline': () => void;
85
86
/** Error during service worker registration */
87
'sw-error': (error: Error) => void;
88
}
89
```
90
91
**Event Usage Examples:**
92
93
```javascript
94
import event from '@sw-event';
95
96
// Service worker is ready
97
event.$on('sw-ready', () => {
98
console.log('[vuepress:sw] Service worker is active.');
99
});
100
101
// Content cached for offline use
102
event.$on('sw-cached', (updateEvent) => {
103
console.log('[vuepress:sw] Content has been cached for offline use.');
104
// updateEvent is an instance of SWUpdateEvent
105
});
106
107
// New content available
108
event.$on('sw-updated', (updateEvent) => {
109
console.log('[vuepress:sw] Content updated.');
110
// Show update notification or auto-update
111
updateEvent.skipWaiting().then(() => {
112
location.reload(true);
113
});
114
});
115
116
// Offline mode detected
117
event.$on('sw-offline', () => {
118
console.log('[vuepress:sw] No internet connection found. App is running in offline mode.');
119
// Show offline indicator
120
});
121
122
// Service worker registration error
123
event.$on('sw-error', (error) => {
124
console.error('[vuepress:sw] Error during service worker registration:', error);
125
// Handle error gracefully
126
});
127
```
128
129
### Service Worker Registration
130
131
Automatic service worker registration that occurs during client-side app enhancement.
132
133
```javascript { .api }
134
/**
135
* Service worker registration configuration
136
* Automatically registered at router.onReady()
137
*/
138
interface ServiceWorkerRegistration {
139
/** URL path to service worker file */
140
url: string; // `${SW_BASE_URL}service-worker.js`
141
142
/** Registration options */
143
registrationOptions: {};
144
145
/** Lifecycle event handlers */
146
handlers: {
147
ready(): void;
148
cached(registration: ServiceWorkerRegistration): void;
149
updated(registration: ServiceWorkerRegistration): void;
150
offline(): void;
151
error(error: Error): void;
152
};
153
}
154
```
155
156
The service worker is automatically registered in production mode when `SW_ENABLED` is true. Registration happens after the Vue router is ready to ensure proper initialization.
157
158
**Production Only**: Service worker registration is automatically disabled in development mode (`process.env.NODE_ENV !== 'production'`) to prevent caching issues during development.
159
160
### Skip-Waiting Message Channel
161
162
Communication mechanism between main thread and service worker for immediate activation.
163
164
```javascript { .api }
165
/**
166
* Skip-waiting communication uses MessageChannel
167
* Service worker listens for 'skip-waiting' message type
168
*/
169
interface SkipWaitingMessage {
170
/** Message type identifier */
171
type: 'skip-waiting';
172
}
173
174
interface SkipWaitingResponse {
175
/** Error if skip-waiting failed, null on success */
176
error: Error | null;
177
}
178
```
179
180
The skip-waiting functionality is handled automatically by the `SWUpdateEvent.skipWaiting()` method using MessageChannel communication.
181
182
## Types
183
184
```javascript { .api }
185
interface ServiceWorkerRegistration {
186
/** Update the service worker registration */
187
update(): Promise<ServiceWorkerRegistration>;
188
/** Waiting service worker instance (if available) */
189
waiting?: ServiceWorker;
190
/** Active service worker instance (if available) */
191
active?: ServiceWorker;
192
/** Installing service worker instance (if available) */
193
installing?: ServiceWorker;
194
}
195
196
interface ServiceWorker {
197
/** Post message to service worker */
198
postMessage(message: any, transfer?: Transferable[]): void;
199
/** Service worker state */
200
state: 'installing' | 'installed' | 'activating' | 'activated' | 'redundant';
201
}
202
```