0
# Workbox Window
1
2
Workbox Window is a TypeScript library that simplifies communication between web applications and Workbox service workers. It provides a comprehensive API for service worker registration, lifecycle management, and bidirectional messaging with full type safety and event-driven architecture.
3
4
## Package Information
5
6
- **Package Name**: workbox-window
7
- **Package Type**: npm
8
- **Language**: TypeScript
9
- **Installation**: `npm install workbox-window`
10
11
## Core Imports
12
13
```typescript
14
import { Workbox, messageSW } from "workbox-window";
15
```
16
17
For CommonJS:
18
19
```javascript
20
const { Workbox, messageSW } = require("workbox-window");
21
```
22
23
All event types and utilities:
24
25
```typescript
26
import {
27
Workbox,
28
messageSW,
29
WorkboxEvent,
30
WorkboxMessageEvent,
31
WorkboxLifecycleEvent,
32
WorkboxLifecycleWaitingEvent,
33
WorkboxLifecycleEventMap,
34
WorkboxEventMap
35
} from "workbox-window";
36
```
37
38
## Basic Usage
39
40
```typescript
41
import { Workbox } from "workbox-window";
42
43
// Create and register service worker
44
const wb = new Workbox("/sw.js");
45
46
// Listen for lifecycle events
47
wb.addEventListener("waiting", (event) => {
48
console.log("Service worker is waiting");
49
// Optionally skip waiting
50
wb.messageSkipWaiting();
51
});
52
53
wb.addEventListener("controlling", (event) => {
54
console.log("Service worker is now controlling the page");
55
window.location.reload();
56
});
57
58
// Register the service worker
59
await wb.register();
60
61
// Send messages to service worker
62
const response = await wb.messageSW({ type: "CACHE_URLS", payload: urls });
63
```
64
65
## Architecture
66
67
Workbox Window is built around several key components:
68
69
- **Workbox Class**: Main interface with event handling capabilities for service worker management
70
- **Event System**: Type-safe event system with lifecycle and message events
71
- **Message Communication**: Promise-based bidirectional communication with service workers
72
- **Lifecycle Management**: Automatic handling of service worker states and transitions
73
- **Registration Control**: Flexible registration options with deferred loading support
74
75
## Capabilities
76
77
### Service Worker Management
78
79
The core Workbox class provides comprehensive service worker registration and lifecycle management.
80
81
```typescript { .api }
82
/**
83
* Main class for service worker registration, updates, and lifecycle management
84
*/
85
class Workbox {
86
/**
87
* Creates a new Workbox instance with a script URL and service worker options
88
* @param scriptURL - The service worker script URL (supports TrustedScriptURL)
89
* @param registerOptions - Service worker registration options
90
*/
91
constructor(scriptURL: string | TrustedScriptURL, registerOptions?: RegistrationOptions);
92
93
/**
94
* Registers the service worker, delaying until window load by default
95
* @param options - Registration options
96
* @param options.immediate - If true, register immediately without waiting for load
97
* @returns Promise resolving to ServiceWorkerRegistration or undefined
98
*/
99
register(options?: { immediate?: boolean }): Promise<ServiceWorkerRegistration | undefined>;
100
101
/**
102
* Checks for updates of the registered service worker
103
* @returns Promise resolving when update check completes
104
*/
105
update(): Promise<void>;
106
107
/**
108
* Returns promise resolving to the service worker instance
109
* @returns Promise resolving to ServiceWorker
110
*/
111
getSW(): Promise<ServiceWorker>;
112
113
/**
114
* Sends data to the service worker and resolves with response
115
* @param data - Object to send to service worker
116
* @returns Promise resolving to response from service worker
117
*/
118
messageSW(data: object): Promise<any>;
119
120
/**
121
* Sends SKIP_WAITING message to waiting service worker
122
*/
123
messageSkipWaiting(): void;
124
125
/**
126
* Promise resolving when service worker becomes active
127
*/
128
readonly active: Promise<ServiceWorker>;
129
130
/**
131
* Promise resolving when service worker starts controlling the page
132
*/
133
readonly controlling: Promise<ServiceWorker>;
134
135
/**
136
* Add event listener for service worker lifecycle and message events
137
* @param type - Event type to listen for
138
* @param listener - Event handler function
139
*/
140
addEventListener<K extends keyof WorkboxEventMap>(
141
type: K,
142
listener: (event: WorkboxEventMap[K]) => any
143
): void;
144
145
/**
146
* Remove event listener for specific event type
147
* @param type - Event type to remove listener from
148
* @param listener - Event handler function to remove
149
*/
150
removeEventListener<K extends keyof WorkboxEventMap>(
151
type: K,
152
listener: (event: WorkboxEventMap[K]) => any
153
): void;
154
}
155
```
156
157
### Message Communication
158
159
Standalone utility for sending messages to service workers with promise-based responses.
160
161
```typescript { .api }
162
/**
163
* Sends data to a service worker via postMessage and resolves with response
164
* @param sw - The service worker to send the message to
165
* @param data - Object to send to the service worker
166
* @returns Promise resolving to response from service worker
167
*/
168
function messageSW(sw: ServiceWorker, data: object): Promise<any>;
169
```
170
171
### Event System
172
173
Type-safe event system for handling service worker lifecycle and messages.
174
175
```typescript { .api }
176
/**
177
* Minimal Event subclass for Workbox events
178
*/
179
class WorkboxEvent<K extends keyof WorkboxEventMap> {
180
constructor(type: K, props: Omit<WorkboxEventMap[K], 'target' | 'type'>);
181
182
type: K;
183
target?: Workbox;
184
sw?: ServiceWorker;
185
originalEvent?: Event;
186
isExternal?: boolean;
187
}
188
```
189
190
## Event Types
191
192
```typescript { .api }
193
/**
194
* Event dispatched when receiving postMessage from service worker
195
*/
196
interface WorkboxMessageEvent extends WorkboxEvent<'message'> {
197
data: any;
198
originalEvent: Event;
199
ports: readonly MessagePort[];
200
}
201
202
/**
203
* Base interface for service worker lifecycle events
204
*/
205
interface WorkboxLifecycleEvent extends WorkboxEvent<keyof WorkboxLifecycleEventMap> {
206
isUpdate?: boolean;
207
}
208
209
/**
210
* Lifecycle event for waiting state with additional context
211
*/
212
interface WorkboxLifecycleWaitingEvent extends WorkboxLifecycleEvent {
213
wasWaitingBeforeRegister?: boolean;
214
}
215
216
/**
217
* Map of lifecycle event types to their event objects
218
*/
219
interface WorkboxLifecycleEventMap {
220
installing: WorkboxLifecycleEvent;
221
installed: WorkboxLifecycleEvent;
222
waiting: WorkboxLifecycleWaitingEvent;
223
activating: WorkboxLifecycleEvent;
224
activated: WorkboxLifecycleEvent;
225
controlling: WorkboxLifecycleEvent;
226
redundant: WorkboxLifecycleEvent;
227
}
228
229
/**
230
* Complete map of all Workbox event types
231
*/
232
interface WorkboxEventMap extends WorkboxLifecycleEventMap {
233
message: WorkboxMessageEvent;
234
}
235
236
/**
237
* Type for event listener callback functions
238
*/
239
type ListenerCallback = (event: WorkboxEvent<any>) => any;
240
```
241
242
## Usage Examples
243
244
### Advanced Registration
245
246
```typescript
247
import { Workbox } from "workbox-window";
248
249
const wb = new Workbox("/sw.js", {
250
scope: "/app/",
251
type: "module"
252
});
253
254
// Register immediately without waiting for load
255
await wb.register({ immediate: true });
256
```
257
258
### Event Handling
259
260
```typescript
261
import { Workbox } from "workbox-window";
262
263
const wb = new Workbox("/sw.js");
264
265
wb.addEventListener("installed", (event) => {
266
if (event.isUpdate) {
267
console.log("Service worker updated");
268
} else {
269
console.log("Service worker installed for first time");
270
}
271
});
272
273
wb.addEventListener("waiting", (event) => {
274
if (event.wasWaitingBeforeRegister) {
275
console.log("Service worker was already waiting");
276
}
277
278
// Show update available notification
279
if (confirm("New version available! Update now?")) {
280
wb.messageSkipWaiting();
281
}
282
});
283
284
wb.addEventListener("message", (event) => {
285
console.log("Message from SW:", event.data);
286
});
287
288
await wb.register();
289
```
290
291
### Service Worker Communication
292
293
```typescript
294
import { Workbox, messageSW } from "workbox-window";
295
296
const wb = new Workbox("/sw.js");
297
await wb.register();
298
299
// Get service worker reference
300
const sw = await wb.getSW();
301
302
// Send message using utility function
303
const response = await messageSW(sw, {
304
type: "GET_CACHE_STATS"
305
});
306
307
// Or send via Workbox instance
308
const response2 = await wb.messageSW({
309
type: "CLEAR_CACHE",
310
cacheName: "images"
311
});
312
```
313
314
### Manual Updates
315
316
```typescript
317
import { Workbox } from "workbox-window";
318
319
const wb = new Workbox("/sw.js");
320
await wb.register();
321
322
// Check for updates periodically
323
setInterval(async () => {
324
await wb.update();
325
}, 60000); // Check every minute
326
```
327
328
### Trusted Types Support
329
330
```typescript
331
import { Workbox } from "workbox-window";
332
333
// Using TrustedScriptURL for enhanced security
334
const trustedURL = trustedTypes
335
.createPolicy("workbox", {
336
createScriptURL: (url) => url
337
})
338
.createScriptURL("/sw.js");
339
340
const wb = new Workbox(trustedURL);
341
await wb.register();
342
```