What is the web Push API?

The Push API lets a web application “subscribe” for notifications from a remote server. The following code will log a PushSubscription object:

navigator.serviceWorker.ready.then(reg => {
  reg.pushManager.subscribe({userVisibleOnly: true}).then(sub => {
    console.log("Subscription:", sub);
    window.sub = sub;

The PushSubscription object has one important property: endpoint, a URL which can be used to send push notifications to this web application. When I run the above, I get an endpoint which looks like:


The Push API spec says that the way to use this URL is described by the “Web Push Protocol”. But this draft spec is expired and vague on details, so it’s currently impossible to do anything with it in a browser-agnostic way. However, I was able to get this working by doing:

$ curl -H 'Authorization: key=MY_SERVER_KEY' -H 'Content-Type: application/json' -d '{"data": {"example":"data"},"to":"SOME_DEVICE_TOKEN"}' https://android.googleapis.com/gcm/send

Hooray, I get a push notification! But this borked API means your application server needs separate logic for every possible push service! This is pretty rough.

Get updates on Twitter

I wrote this because I felt like it. This post is not associated with my employer. This site is hosted by Netlify (who are great, but I'm not associated with them either).