diff --git a/app/models/user/push_notification_methods.rb b/app/models/user/push_notification_methods.rb index 01138633..fd8eae03 100644 --- a/app/models/user/push_notification_methods.rb +++ b/app/models/user/push_notification_methods.rb @@ -9,11 +9,17 @@ module User::PushNotificationMethods n.app = app n.registration_ids = [s.subscription.symbolize_keys] n.data = { - message: resource.as_push_notification.to_json + message: resource.as_push_notification.merge(notification_data).to_json, } n.save! PushNotificationWorker.perform_async(n.id) end end + + def notification_data = { + data: { + badge: current_user.unread_inbox_count, + }, + } end diff --git a/public/service_worker.js b/public/service_worker.js index 8662f085..3e88521c 100644 --- a/public/service_worker.js +++ b/public/service_worker.js @@ -11,27 +11,22 @@ const OFFLINE_CACHE_PATHS = [ self.addEventListener('push', function (event) { if (event.data) { - const notification = event.data.json(); + const contents = event.data.json(); + navigator.setAppBadge(contents.data.badge); - event.waitUntil(self.registration.showNotification(notification.title, { - body: notification.body, - tag: notification.type, - icon: notification.icon, - })); + event.waitUntil(self.registration.showNotification(contents.title, contents)); } else { console.error("Push event received, but it didn't contain any data.", event); } }); self.addEventListener('notificationclick', async event => { - if (event.notification.tag === 'inbox') { + if ("click_url" in event.notification.data) { event.preventDefault(); - return clients.openWindow("/inbox", "_blank").then(result => { + return clients.openWindow(event.notification.data.click_url, "_blank").then(result => { event.notification.close(); return result; }); - } else { - console.warn(`Unhandled notification tag: ${event.notification.tag}`); } });