【发布时间】:2020-10-08 19:43:15
【问题描述】:
self.setTimeout 在预期延迟后可靠地触发 self.registration.showNotification,仅在浏览器未被最小化/隐藏的情况下。
它似乎在 20 秒后起作用。之后,它默默地失败了。
我还没有确定是self.setTimeout没有运行回调,还是self.registration.showNotification没有显示通知。
代码:
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);
}
})
【问题讨论】:
标签: javascript push-notification notifications service-worker