Stephen
Stephen

Reputation: 523

Service Work and Push Notifications

I am currently trying to implement Push Notifications into my website and I am having trouble trying to display a dynamic title and link.

This is what my service worker currently looks like

self.addEventListener( 'push', function(event) {
    // console.log( '[Service Worker] Push Received.' );
    // console.log( '[Service Worker] Push has this data: ' );

    const title = event.data.title;
    const options = {
        body: event.data.text(),
    }

    const notificationPromise = self.registration.showNotification(title, options);
    event.waitUntil(notificationPromise);
} );

self.addEventListener( 'notificationclick', function( event ) {
    console.log( '[Service Worker] Notification click Received.' );

    event.notification.close();

    event.waitUntil(
        clients.openWindow( 'https://developers.google.com' )
    );
} )

As you can see currently the link is a hard-coded developers.google.com link and the title returns 'undefined'

Screenshot of Notification

Is there anything I have to do from the backend of the website to send these into the payload?

In case it helps I am using the Web Push Library for C#

Upvotes: 0

Views: 274

Answers (1)

Stephen Archer
Stephen Archer

Reputation: 1004

I believe this is actually an issue with how you're accessing the title data from the json object.

To access the event.data object as a json object, you have to call the json() method on the data object. So something like this:

const title = event.data.json().title;

Upvotes: 1

Related Questions