Skip to content

Commit 50b3e9f

Browse files
SkyZeroZxthePunderWoman
authored andcommitted
docs: Adds guide for extending Angular service worker (angular#63629)
Documents how to create custom service worker scripts to handle push notifications, background sync, and other events by importing and extending Angular's default behavior PR Close angular#63629
1 parent b62cadb commit 50b3e9f

File tree

2 files changed

+116
-0
lines changed

2 files changed

+116
-0
lines changed

adev/src/app/sub-navigation-data.ts

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -985,6 +985,11 @@ const DOCS_SUB_NAVIGATION_DATA: NavigationItem[] = [
985985
path: 'ecosystem/service-workers/getting-started',
986986
contentPath: 'ecosystem/service-workers/getting-started',
987987
},
988+
{
989+
label: 'Custom service worker scripts',
990+
path: 'ecosystem/service-workers/custom-service-worker-scripts',
991+
contentPath: 'ecosystem/service-workers/custom-service-worker-scripts',
992+
},
988993
{
989994
label: 'Configuration file',
990995
path: 'ecosystem/service-workers/config',
Lines changed: 111 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,111 @@
1+
# Custom service worker scripts
2+
3+
While the Angular service worker provides excellent capabilities, you may need to add custom functionality such as handling push notifications, background sync, or other service worker events. You can create a custom service worker script that imports and extends the Angular service worker.
4+
5+
## Creating a custom service worker
6+
7+
To create a custom service worker that extends Angular's functionality:
8+
9+
1. Create a custom service worker file (e.g., `custom-sw.js`) in your `src` directory:
10+
11+
<docs-code language="javascript">
12+
13+
// Import the Angular service worker
14+
importScripts('./ngsw-worker.js');
15+
16+
(function () {
17+
'use strict';
18+
19+
// Add custom notification click handler
20+
self.addEventListener('notificationclick', (event) => {
21+
console.log('Custom notification click handler');
22+
console.log('Notification details:', event.notification);
23+
24+
// Handle notification click - open URL if provided
25+
if (clients.openWindow && event.notification.data.url) {
26+
event.waitUntil(clients.openWindow(event.notification.data.url));
27+
console.log('Opening URL:', event.notification.data.url);
28+
}
29+
});
30+
31+
// Add custom background sync handler
32+
self.addEventListener('sync', (event) => {
33+
console.log('Custom background sync handler');
34+
35+
if (event.tag === 'background-sync') {
36+
event.waitUntil(doBackgroundSync());
37+
}
38+
});
39+
40+
function doBackgroundSync() {
41+
// Implement your background sync logic here
42+
return fetch('https://example.com/api/sync')
43+
.then(response => response.json())
44+
.then(data => console.log('Background sync completed:', data))
45+
.catch(error => console.error('Background sync failed:', error));
46+
}
47+
})();
48+
49+
</docs-code>
50+
51+
2. Update your `angular.json` file to use the custom service worker:
52+
53+
<docs-code language="json">
54+
55+
{
56+
"projects": {
57+
"your-app": {
58+
"architect": {
59+
"build": {
60+
"options": {
61+
"assets": [
62+
{
63+
"glob": "**/*",
64+
"input": "public"
65+
},
66+
"app/src/custom-sw.js"
67+
]
68+
},
69+
}
70+
}
71+
}
72+
}
73+
}
74+
75+
</docs-code>
76+
77+
3. Configure the service worker registration to use your custom script:
78+
79+
<docs-code language="typescript">
80+
81+
import { ApplicationConfig, isDevMode } from '@angular/core';
82+
import { provideServiceWorker } from '@angular/service-worker';
83+
84+
export const appConfig: ApplicationConfig = {
85+
providers: [
86+
provideServiceWorker('custom-sw.js', {
87+
enabled: !isDevMode(),
88+
registrationStrategy: 'registerWhenStable:30000'
89+
}),
90+
],
91+
};
92+
93+
</docs-code>
94+
95+
### Best practices for custom service workers
96+
97+
When extending the Angular service worker:
98+
99+
- **Always import the Angular service worker first** using `importScripts('./ngsw-worker.js')` to ensure you get all the caching and update functionality
100+
- **Wrap your custom code in an IIFE** (Immediately Invoked Function Expression) to avoid polluting the global scope
101+
- **Use `event.waitUntil()`** for asynchronous operations to ensure they complete before the service worker is terminated
102+
- **Test thoroughly** in both development and production environments
103+
- **Handle errors gracefully** to prevent your custom code from breaking the Angular service worker functionality
104+
105+
### Common use cases
106+
107+
Custom service workers are commonly used for:
108+
109+
- **Push notifications**: Handle incoming push messages and display notifications
110+
- **Background sync**: Sync data when the network connection is restored
111+
- **Custom navigation**: Handle special routing or offline page scenarios

0 commit comments

Comments
 (0)