PWA 可以在关闭时安排通知吗?

Can a PWA schedule notifications when closed?

我正在开发一个 TODO-list PWA,它应该每天在 8:00am 显示当天的任务,即使应用程序已关闭(类似于闹钟)。

有没有办法用 PWA 实现这一点? (主要针对Chrome/Android)

到目前为止,在我的 service worker 中我有(简化)


self.addEventListener("message", (event) => {
    // Workflow: The app sends a message that the timer should be set.
    const prom = new Promise((resolveIt) =>
      self.setTimeout(() => showAlarmAndResolve(resolveIt, event.data), '<timeout_in_ms>')
    );
    // tell the service worker to remain alive until promise is resolved
    event.waitUntil(prom); 
  }
});

async function showAlarmAndResolve(resolveIt, text) {
  const options = {
    body: text,
    tag: "todo-alert",
  };
  await self.registration.showNotification(
    "Your tasks for today",
    options
  );
  resolveIt();   // allow the service worker to terminate
}

如果没有 event.waitUntil,当我关闭 phone 上的应用程序(或关闭浏览器选项卡)时不会显示通知,但会显示。 然而,让 service worker 存活半天似乎是一个非常糟糕的主意 - 此外,我读到(此处:Best practice for keeping timer running in PWA)在 Android 上,service worker 可能会在大约 20 分钟后终止.

如何实现这样的闹钟功能?

一些(较旧的)问题并没有真正提供那么多帮助/希望...
Background events in progressive web apps? (building an alarm clock app)

Chrome 通过 Notification Triggers, and after running an origin trial, the team decided not to move ahead. If anything changes, there will be updates in the Chromium issue tracker.

试验了此功能

您可以使用 Periodic Background Sync API 实现类似的 once-a-day 功能,但不保证 白天 事件将触发。如果您的用户需要精确控制何时显示通知,这将无济于事。此外,仅当用户完成了 PWA 的安装流程时才支持它。