Two Service Worker & Push Notification GOTCHAs

I have spent my day diving into Service Workers and Push Notifications since I wanted my webapp STQ (a German Star Trek trivia quiz app) to send out push messages to users. This has probably been the most wanted feature ever since.

Addy Osmani’s guide on PWAs and this codelab by Sam Dutton on implementing push notifications are a great start. But since the technology is still cutting edge, there were a two gotchas along my way, which I want to share.

Gotcha #1: SW not in root folder of app

There was an issue that the navigator.serviceWorker.ready promise was never fulfilled. After a while I found out, the problem was that the service worker file was stored in an assets sub-directory but not in the root directory of the app. Read this: http://stackoverflow.com/a/29874095/3890888

Gotcha #2: A registered SW is not an active SW

The sample code on the Google website on how to subscribe to push events is a bit outdated:

screenshot sub code
CC-BY 3.0 Sam Dutton (Screenshot taken on 28.07.2016)

In the example above, they try to subscribe as soon as the SW is installed, even though it is not yet ready. In Chrome 52, this results in an exception

It took me a while to discover that the sample code in the repository is fixed. So look at this code:

https://github.com/GoogleChrome/push-notifications/blob/master/completed/06-notification/js/main.js

When registering the SW, you have to wait for the promise navigator.serviceWorker.ready to be fulfilled, so return this promise in the function that is fired, when the SW has been installed.

Further important stuff

  • With event.skipWaiting(), you can skip the waiting state of a new SW, so that it becomes immediately active. Very neat! More info on MDN.
  • chrome://serviceworker-internals/ is splendid for debugging SWs!
  • Use POST, not GET when sending push triggers to Google GCM.

Hope, these hints might save you some trouble.

Leave a Reply

Your email address will not be published. Required fields are marked *