All files service-worker.ts

9.38% Statements 3/32
0% Branches 0/8
0% Functions 0/6
9.68% Lines 3/31

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 561x   1x   1x                                                                                                      
import * as notifications from './notifications';
 
console.log('peerstack service worker');
 
export async function init(self) {
  self.addEventListener('push', function(event) {
    event.waitUntil(new Promise<void>(async (resolve, reject) => {
      try {
        const payload = event.data?.text();
        await notifications.processWebPushNotification(self, payload);
        resolve();
      } catch (err) {
        console.error('error receiving push message', err)
        reject(err);
      }
    }))
  });
  
  self.addEventListener('notificationclick', event => {
    const rootUrl = new URL('/', location as any).href;
    event.notification.close();
    // Enumerate windows, and call window.focus(), or open a new one.
    event.waitUntil(new Promise<void>(async (resolve, reject) => {
      try {
        const notification = event.notification.data as notifications.INotification;
        const clients = await self.clients.matchAll({
          type: 'window',
          includeUncontrolled: true
        });
        let client;
        for(let _client of clients) {
          Iif (_client.url === rootUrl) {
            // matched a client via url so focusing on that
            client = _client;
          }
        }
        Iif (clients[0]) {
          // didn't match any clients via url but have at least one so focusing on last one
          client = clients[clients.length-1];
        }
        if (client) {
          await client.focus();
        } else {
          // no clients found so opening new window
          client = await self.clients.openWindow(`/#${notification.id}`);
          await new Promise(resolve => setTimeout(resolve, 1000));
        }
        await client.postMessage({ type: "NotificationClicked", notification });
        return resolve();
      } catch (err) {
        console.error('Error handling notification click', err);
        reject(err);
      }
    }));
  });
}