Handle going to notification URL on click

Signed-off-by: Thomas Citharel <tcit@tcit.fr>
This commit is contained in:
Thomas Citharel 2021-06-17 16:00:20 +02:00
parent 2c12138f00
commit d1c31a5080
No known key found for this signature in database
GPG Key ID: A061B9DDE0CA0773
2 changed files with 34 additions and 15 deletions

View File

@ -11,7 +11,12 @@ import { CacheableResponsePlugin } from "workbox-cacheable-response";
import { ExpirationPlugin } from "workbox-expiration"; import { ExpirationPlugin } from "workbox-expiration";
import { precacheAndRoute } from "workbox-precaching"; import { precacheAndRoute } from "workbox-precaching";
import { IPushNotification } from "./types/push-notification";
/// <reference lib="WebWorker" />
// export empty type because of tsc --isolatedModules flag
export type {};
declare const self: ServiceWorkerGlobalScope;
// Use with precache injection // Use with precache injection
// eslint-disable-next-line @typescript-eslint/ban-ts-comment // eslint-disable-next-line @typescript-eslint/ban-ts-comment
@ -77,24 +82,45 @@ registerRoute(
}) })
); );
self.addEventListener("push", async (event: any) => { self.addEventListener("push", async (event: PushEvent) => {
const payload = event.data.json() as IPushNotification; if (!event.data) return;
const payload = event.data.json();
console.log("received push", payload); console.log("received push", payload);
const options = { const options = {
title: payload.title,
body: payload.body, body: payload.body,
icon: "/img/icons/android-chrome-512x512.png", icon: "/img/icons/android-chrome-512x512.png",
badge: "/img/icons/badge-128x128.png", badge: "/img/icons/badge-128x128.png",
timestamp: new Date(payload.timestamp), timestamp: new Date(payload.timestamp).getTime(),
lang: payload.locale, lang: payload.locale,
data: { data: {
dateOfArrival: Date.now(), dateOfArrival: Date.now(),
url: payload.url,
}, },
}; };
event.waitUntil(self.registration.showNotification(payload.title, options));
});
self.addEventListener("notificationclick", function (event: NotificationEvent) {
const url = event.notification.data.url;
event.notification.close();
// This looks to see if the current is already open and
// focuses if it is
event.waitUntil( event.waitUntil(
// eslint-disable-next-line @typescript-eslint/ban-ts-comment (async () => {
// @ts-ignore const clientList = await self.clients.matchAll({
self.registration.showNotification(payload.title, options) type: "window",
});
for (let i = 0; i < clientList.length; i++) {
const client = clientList[i] as WindowClient;
if (client.url == url && "focus" in client) {
return client.focus();
}
}
if (self.clients.openWindow) {
return self.clients.openWindow(url);
}
})()
); );
}); });

View File

@ -1,7 +0,0 @@
export interface IPushNotification {
title: string;
body: string;
url: string;
timestamp: string;
locale: string;
}