Skip to content

Commit

Permalink
Add callback support to push notifications (home-assistant#90)
Browse files Browse the repository at this point in the history
* Add callback support to push notifications

* Syntax fix

* Fix callbacks for initial push event

* Add JWT.

* Whoops, jwt was grabbed from the wrong spot
  • Loading branch information
robbiet480 authored and balloob committed Aug 17, 2016
1 parent dd6ee95 commit b90b8f8
Showing 1 changed file with 29 additions and 2 deletions.
31 changes: 29 additions & 2 deletions script/service-worker.js.tmpl
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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)
});
}

0 comments on commit b90b8f8

Please sign in to comment.