web-push-libs / web-push-csharp

Web Push library for C#
Mozilla Public License 2.0
429 stars 108 forks source link

Details on integration with Angular #43

Closed feugen24 closed 2 years ago

feugen24 commented 6 years ago

Hi,

It took me a while to make it work with angular due to payload format and maybe this will be useful for others or maybe added in docs.

In angular 5 the client side processing is typically done in a ngsw-worker.js file and it probably integrates well with node.js api but in order to make it work it needs a specific payload format.

In short the sending of the notification should be done like this:

webPushClient.SendNotification(subscription, JsonConvert.SerializeObject(new { notification = new {title = "title", body = "message"} }), vapidDetails);

where the inner notification object accepts properties from the webpush standard :

//https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerRegistration/showNotification // 0:"actions" // 1:"body" // 2:"dir" // 3:"icon" // 4:"lang" // 5:"renotify" // 6:"requireInteraction" // 7:"tag" // 8:"vibrate" // 9:"data"

thees values are taken from NOTIFICATION_OPTION_NAMES with debug (see bellow js code)

code from ngsw-worker.js:

    async handlePush(data) {
        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]);
        this.scope.registration.showNotification(desc['title'], options);
    }

Notice that if it doesn't find expected format it just returns and you won't see anything on the browser.

 if (!data.notification || !data.notification.title) {
            return;
 }