From 6bfbd7316234999c65476a23d4d5bf77c77d0fda Mon Sep 17 00:00:00 2001 From: Dobromir Popov Date: Sun, 7 Apr 2024 23:14:00 +0300 Subject: [PATCH] service worker for push notifications --- worker/index.js | 39 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 worker/index.js diff --git a/worker/index.js b/worker/index.js new file mode 100644 index 0000000..3e5018f --- /dev/null +++ b/worker/index.js @@ -0,0 +1,39 @@ +'use strict' + +self.addEventListener('push', function (event) { + const data = JSON.parse(event.data.text()) + event.waitUntil( + registration.showNotification(data.title, { + body: data.message, + icon: '/icons/android-chrome-192x192.png' + }) + ) +}) + +self.addEventListener('notificationclick', function (event) { + event.notification.close() + event.waitUntil( + clients.matchAll({ type: 'window', includeUncontrolled: true }).then(function (clientList) { + if (clientList.length > 0) { + let client = clientList[0] + for (let i = 0; i < clientList.length; i++) { + if (clientList[i].focused) { + client = clientList[i] + } + } + return client.focus() + } + return clients.openWindow('/') + }) + ) +}) + +// self.addEventListener('pushsubscriptionchange', function(event) { +// event.waitUntil( +// Promise.all([ +// Promise.resolve(event.oldSubscription ? deleteSubscription(event.oldSubscription) : true), +// Promise.resolve(event.newSubscription ? event.newSubscription : subscribePush(registration)) +// .then(function(sub) { return saveSubscription(sub) }) +// ]) +// ) +// }) \ No newline at end of file