From b90b8f87bc3419d7a2bae31053e1999f8f39166b Mon Sep 17 00:00:00 2001 From: Robbie Trencheny Date: Tue, 16 Aug 2016 23:57:42 -0700 Subject: [PATCH] Add callback support to push notifications (#90) * Add callback support to push notifications * Syntax fix * Fix callbacks for initial push event * Add JWT. * Whoops, jwt was grabbed from the wrong spot --- script/service-worker.js.tmpl | 31 +++++++++++++++++++++++++++++-- 1 file changed, 29 insertions(+), 2 deletions(-) diff --git a/script/service-worker.js.tmpl b/script/service-worker.js.tmpl index dc2feadd25..cee00288fc 100644 --- a/script/service-worker.js.tmpl +++ b/script/service-worker.js.tmpl @@ -2,17 +2,25 @@ self.addEventListener("push", function(event) { var data; if (event.data) { data = event.data.json(); - event.waitUntil(self.registration.showNotification(data.title, data)); + event.waitUntil( + self.registration.showNotification(data.title, data) + .then(function(notification){ + firePushCallback({type: "push", tag: data.tag}, data.data.jwt); + }) + ); } }); self.addEventListener('notificationclick', function(event) { var url; + notificationEventCallback(event); + + event.notification.close(); + if (!event.notification.data || !event.notification.data.url) { return; } - event.notification.close(); url = event.notification.data.url; if (!url) return; @@ -37,3 +45,22 @@ self.addEventListener('notificationclick', function(event) { }) ); }); +self.addEventListener('notificationclose', function(event) { + notificationEventCallback(event); +}); + +function notificationEventCallback(event){ + firePushCallback({ + type: event.type, + tag: event.notification.tag, + action: event.action + }, event.notification.data.jwt); +} +function firePushCallback(data, jwt){ + fetch('/api/notify.html5/callback', { + method: 'POST', + headers: new Headers({'Content-Type': 'application/json', + 'Authorization': 'Bearer '+jwt}), + body: JSON.stringify(data) + }); +}