Skip to content

Commit 9468b6a

Browse files
committed
Handle body from payload
1 parent 531e7bd commit 9468b6a

File tree

2 files changed

+30
-10
lines changed

2 files changed

+30
-10
lines changed

PushMessageFromServer.js

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -28,5 +28,5 @@ webpush.setVapidDetails(
2828
// }
2929
// };
3030

31-
const notification = { title: `Hello at ${(new Date()).toISOString()}` };
32-
webpush.sendNotification(pushSubscription, JSON.stringify(notification));
31+
const payload = { title: `Hello at ${(new Date()).toISOString()}` };
32+
webpush.sendNotification(pushSubscription, JSON.stringify(payload));

public/service-worker.js

Lines changed: 28 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,31 @@
1+
// https://developers.google.com/web/ilt/pwa/introduction-to-push-notifications
2+
// https://web-push-book.gauntface.com/display-a-notification/
13
self.addEventListener('push', (event) => {
2-
const data = event.data.json();
4+
// https://developer.mozilla.org/en-US/docs/Web/API/PushEvent/data
5+
const payload = event.data.json();
6+
7+
const options = {
8+
body: payload.body,
9+
vibrate: [300, 100, 400], // Vibrate 300ms, pause 100ms, then vibrate 400ms
10+
icon: './favicon.ico',
11+
//image: '',
12+
// The notification object includes a tag attribute that is the grouping key.
13+
// When creating a notification with a tag and there is already a notification with the same tag visible to the user,
14+
// the system automatically replaces it without creating a new notification.
15+
tag: 'vibration-sample',
16+
actions: [
17+
{
18+
// https://developers.google.com/web/ilt/pwa/introduction-to-push-notifications#the_notificationclick_event
19+
action: 'open-a-link',
20+
title: 'Open a link',
21+
//icon: '/demos/notification-examples/images/action-1-128x128.png'
22+
}
23+
],
24+
}; // end of options
25+
326
event.waitUntil(
4-
self.registration.showNotification(data.title, {
5-
body: 'Buzz! Buzz!',
6-
vibrate: [300, 100, 400], // Vibrate 300ms, pause 100ms, then vibrate 400ms
7-
icon: './favicon.ico',
8-
tag: 'vibration-sample'
9-
})
27+
self.registration.showNotification(payload.title, options)
1028
);
11-
});
29+
});
30+
31+
// https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerGlobalScope/notificationclick_event#examples

0 commit comments

Comments
 (0)