简体   繁体   中英

Delay an HTML5 notification?

I've been looking at the state of HTML notifications and service workers, and was wondering - is it possible to show a notification on a delay? Basically, I would like to be able to say "remind me in 30 minutes" (or whatever), then push a notification to the user 30 minutes later. That could be scheduled immediately, but I'm not seeing any functionality that allows it.

Am I missing something or is it impossible in the current state of (particularly) Chrome APIs?

This is possible but not straightforward with service workers, at least in their present form. It's not straightforward because a service worker can't keep itself awake for half an hour or wake itself up with a setTimeout or setInterval . The browser will just shut the worker down and will keep no record of any timeouts or intervals. You could wake it up with a message from an open tab, but you said that you don't want to have to have to keep an open tab, and if you assume an open tab then why even bother with the service worker anyway? As Jeff Posnick suggested in a comment, you could perhaps eventually use the Sync or PeriodicSync APIs, but, as he also points out, they aren't implemented yet and aren't really intended for this anyway.

You can accomplish what you want in current versions of Chrome using the Push API , but you'll have to include the server in the loop and set yourself up with a push notification service (ie GCM). Here's how it would work, roughly:

  • When you decide to delay a notification, let the server know about it
  • After a delay, the server sends out a push message for your user
  • The service worker is woken up in response to the push and creates a new notification

This last part will be a hassle, because currently you can't actually send any kind of payload with a push, so your service worker will need some way of figuring out what the notification is supposed to be. Maybe the server has a list of snoozed notifications and the service worker can get it from there, or maybe you saved them in IndexedDB.

Adapted from https://developer.cdn.mozilla.net/media/uploads/demos/e/l/elfoxero/c17223c414d8ddafb7808972b5617d9e/html5-notifications_1400214081_demo_package/ :

<script>
    var Notification = window.Notification || window.mozNotification || window.webkitNotification;

    function show() {
        window.setTimeout(function () {
            var instance = new Notification("Hello World!");
        }, 5000);

        return false;
    }
</script>

<a href="#" onclick="return show()">Notify me!</a>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM