Angular 7 PWA configure Push Notifications
After lots of struggle I found something and will share it for others:
Digging into the ngsw-worker.js that is created by running build --prod there is this function:
onPush(msg) {
// Push notifications without data have no effect.
if (!msg.data) {
return;
}
// Handle the push and keep the SW alive until it's handled.
msg.waitUntil(this.handlePush(msg.data.json()));
}
...
handlePush(data) {
return __awaiter$5(this, void 0, void 0, function* () {
yield this.broadcast({
type: 'PUSH',
data,
});
if (!data.notification || !data.notification.title) {
return;
}
const desc = data.notification;
let options = {};
NOTIFICATION_OPTION_NAMES.filter(name => desc.hasOwnProperty(name))
.forEach(name => options[name] = desc[name]);
yield this.scope.registration.showNotification(desc['title'], options);
});
}
As it looks like angular subscribes and shows the notification for you, it is not necessary to subscribe and show it in your own code. I had an issue with my sending library (https://github.com/laravel-notification-channels/webpush) that was sending the payload like this:
payload = {"title":"test","actions":[{"title":"View App","action":"view_app"}],"body":"test","icon":"\/icon.png","data":{"id":"21a3804e-6d71-4a56-b513-535709c37c0f"}}
but angular expects obviously something like:
payload = {
"notification":{"title":"test","actions":[{"title":"View App","action":"view_app"}],"body":"test","icon":"\/icon.png","data":{"id":"21a3804e-6d71-4a56-b513-535709c37c0f"}}
}
which caused this line in ngsw-worker.js to fail:
if (!data.notification || !data.notification.title) {
return;
}
Therefor, no notification was shown, but the browser reported an update in the background. Hope this helps someone.
Is there a way to handle click events on the notifications?
Try this:
this.swPush.notificationClicks.subscribe(data => {
// handle click
})