【问题标题】:Deferring a Notification in ServiceWorker when browser/pwa is Minimized当浏览器/pwa 最小化时延迟 ServiceWorker 中的通知
【发布时间】: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


    【解决方案1】:

    当服务工作者“看起来”空闲时,它会被浏览器主动杀死。

    如果您想要在保持 Service Worker 活动的同时执行异步工作,则需要在 Promise 内执行该工作,然后将其传递给 event.waitUntil()。这不会让 Service Worker 永远活着,但它会告诉浏览器延长 Service Worker 的生命周期,直到 Promise 解析或浏览器特定的时间限制(通常是几分钟)过去。

    任何从ExtendableEvent 继承的服务工作者事件,包括MessageEvent,都会公开waitUntil() 方法。

    不过,您需要稍微重写代码,以将 setTimeout() 调用转换为 something that's Promise-friendly。

    【讨论】:

    • 嗨,杰夫,谢谢。我更新了 OP 中的代码。你觉得这对吗?我只是用设置了 5 分钟的计时器对其进行了测试,不幸的是它没有工作。您提到了“特定于浏览器的时间限制”...
    • 顺便说一句,在桌面 Chrome 上,5 分钟计时器有效。在 Android Chrome 上,5 分钟计时器最终在大约 8 分钟后触发。我在 5 分钟时重新打开了浏览器,然后将其最小化。
    • 我自己无法运行代码,但我认为这是一般的想法。每个浏览器在杀死 SW 之前等待 Promise 传递给 waitUntil() 解决的时间量因浏览器和操作系统而异。不幸的是,没有任何保证。
    猜你喜欢
    • 1970-01-01
    • 2011-12-12
    • 1970-01-01
    • 2020-12-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多