self.setTimeout reliably fires self.registration.showNotification after the expected delay, only under the condition the browser is NOT minimized / hidden.
It seems to work up to 20 seconds later. After that, it silently fails.
I have not yet determined if it is the self.setTimeout which fails to run the callback, or if it is the self.registration.showNotification fails to show the notification.
Code:
importScripts('./ngsw-worker.js');
let pendingNotifications = new Map();
function wait(ms, pendingNotification) {
return new Promise(resolve => {
pendingNotification.TimerId = setTimeout(resolve, ms);
});
}
async function processNotification(data, pendingNotification) {
let delay = await wait(data.Data.DeferredSeconds * 1000, pendingNotification);
//let notCancelled = pendingNotifications.has(data.Data.CancellationToken);
pendingNotifications.delete(data.Data.CancellationToken);
//if (notCancelled) {
self.registration.showNotification(data.Data.Title, { icon: data.Data.Icon, vibrate: data.Data.VibrationPattern, body: data.Data.Body });
//}
return null;
}
self.addEventListener('message', function (messageEvent) {
let data = messageEvent.data;
if (data == null) {
return;
}
if (data.Type == "Notification") {
let pendingNotification = {
TimerId: -1,
CancellationToken: data.Data.CancellationToken
};
pendingNotifications.set(data.Data.CancellationToken, pendingNotification);
messageEvent.waitUntil(processNotification(data, pendingNotification));
}
if (data.Type == "NotificationCancel") {
let pendingNotification = pendingNotifications.get(data.Data.CancellationToken);
if (pendingNotification == null) {
return;
}
self.clearTimeout(pendingNotification.TimerId);
pendingNotifications.delete(pendingNotification.CancellationToken);
}
})