Instructor: In serviceworker.js we need to save access to the service worker registration here. Set global.registration to the registration. Then in app.js we can make a new button which will ask for permission to subscribe the user to push notifications. Then in the onclick function for that button, we can ask the user for push notification permission.
First, we need a public key for our PAS server. For this demo we'll generate a new key by globally installing Web Push with npm. Then by running Web Push generate VAPID keys, which will give us a new public and private key. Let's copy the public key, and then back in app.js paste that key into the new subscribe function.
Then we'll copy a function from the Google documentation about push notifications called urlB64ToUint8Array, which will convert that public key as a string into an array that can actually be used by the browser to subscribe to push notifications.
Then in our subscribe method we can access the service worker registration that we stored on global and call subscribe on the PushManager. That function is a promise, so we'll know that the user is subscribed successfully once we get a promise resolution.
In sw.js we can listen for a push event from the push server just like we did for fetch. Add a push event listener. We're going to tell the event to wait until we show a push notification. Access the server worker registration with self.registration and call show notification.
That takes the title as the first argument and a hash of options as the second. For now, we'll set the icon to an icon that we already have in the public folder and the body to whatever text comes through the push from the server. Now we can build and serve that to test the notification.
Google Chrome's DevTools currently has a bug with testing push notifications. I'm using Google Canary here, which has fixed the issue. First go to the profile page and click the button to subscribe to push notifications.
Once we click allow, you'll see a message in the console that confirms that we can now receive push notifications from this PWA. Then in the application tab of DevTools, locate the push test location. Then we can fill in a message like "New to do item added." When we click push we see the notification.
Also, in app.js we can trigger a push notification from our app directly instead of from a third party server. Add a new button and we'll make a new test push message function. In that function we'll call the global registration that we said earlier.
Here we can call show notification directly passing in a title and a body. When we build and serve that we can go to the profile page and click the button and see our successful push test triggered from the app code itself.