Web Push Notifications with Web Workers
Did you know that you can now send push notifications to a browser even when the user is no longer on the page? The notification API allows you to pop up OS level notifications from JavaScript. With Web Workers you are able to register a worker permanently in a browser that will handle these notifications offline. I’m going to outline how to do this with Google Chrome and Google Cloud Messaging.
Before I go into details, the sample code for all steps and components is here.
Here is an example workflow, with the accompanying diagram.
- Browsers asks for permissions to send notification.
- Register your web worker web worker.
- When registration comes back, subscribe to push on the registration object.
- when subscription endpoint comes back from the API, then you need to send this ID to your server.
- Fire off push notifications to the endpoint id from your server (this is the push notification subscription ID).
- Listen in your worker for “push” event and show messages.
Written on July 3, 2016