UNPKG

1.71 kBJavaScriptView Raw
1// The Lounge - https://github.com/thelounge/lounge
2/* global clients */
3"use strict";
4
5self.addEventListener("message", function(event) {
6 showNotification(event, event.data);
7});
8
9self.addEventListener("push", function(event) {
10 if (!event.data) {
11 return;
12 }
13
14 showNotification(event, event.data.json());
15});
16
17function showNotification(event, payload) {
18 if (payload.type !== "notification") {
19 return;
20 }
21
22 // get current notification, close it, and draw new
23 event.waitUntil(
24 self.registration
25 .getNotifications({
26 tag: `chan-${payload.chanId}`,
27 })
28 .then((notifications) => {
29 for (const notification of notifications) {
30 notification.close();
31 }
32
33 return self.registration.showNotification(payload.title, {
34 tag: `chan-${payload.chanId}`,
35 badge: "img/logo-64.png",
36 icon: "img/touch-icon-192x192.png",
37 body: payload.body,
38 timestamp: payload.timestamp,
39 });
40 })
41 );
42}
43
44self.addEventListener("notificationclick", function(event) {
45 event.notification.close();
46
47 event.waitUntil(clients.matchAll({
48 includeUncontrolled: true,
49 type: "window",
50 }).then((clientList) => {
51 if (clientList.length === 0) {
52 if (clients.openWindow) {
53 return clients.openWindow(`.#${event.notification.tag}`);
54 }
55
56 return;
57 }
58
59 const client = findSuitableClient(clientList);
60
61 client.postMessage({
62 type: "open",
63 channel: event.notification.tag,
64 });
65
66 if ("focus" in client) {
67 client.focus();
68 }
69 }));
70});
71
72function findSuitableClient(clientList) {
73 for (let i = 0; i < clientList.length; i++) {
74 const client = clientList[i];
75
76 if (client.focused || client.visibilityState === "visible") {
77 return client;
78 }
79 }
80
81 return clientList[0];
82}