5

I'm developing a TODO-list PWA which should display the tasks of the day every day at 8:00am, even when the app is closed (similar to an alarm clock).

Is there a way to achieve this with PWAs? (Mainly targeting Chrome/Android)

So far, in my service worker I have (simplified)


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
}

Without the event.waitUntil, the notification is not displayed when I close the app on my phone (or close the browser tab), with it, it is displayed. However, keeping the service worker alive for half a day somehow seems like a really bad idea - and furthermore, I read (here: Best practice for keeping timer running in PWA) that on Android the service worker might terminate anyway after ~20 minutes.

How can I implement such an alarm clock like functionality?

Some (older) questions do not really give that much help / hope...
Background events in progressive web apps? (building an alarm clock app)
Is it possible to set the alarm by PWA? (building a timer/alarm clock app)

Moritz
  • 1,085
  • 1
  • 8
  • 20
  • To everyone who wants this functionality, please star and comment on the Google issue requesting it to motivate them to act: https://bugs.chromium.org/p/chromium/issues/detail?id=889077 – Richard Jun 09 '22 at 08:49

1 Answers1

5

Chrome experimented with this functionality via 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.

You can achieve similar once-a-day functionality, without any guarantees about when during the day the event will fire, by using the Periodic Background Sync API. If your users needed exact control over when the notification is shown, this wouldn't help. Additionally, it's only supported if a user has gone through the installation flow for your PWA.

Jeff Posnick
  • 53,580
  • 14
  • 141
  • 167
  • 1
    Ok, this answers the question, so despite saying "no, that's not possible", thank you for that explanation! Meanwhile, I started to use push notifications with a cron job for that purpose ... not really happy about this, but it'll do the job for my use case. – Moritz Jan 27 '22 at 21:27