3

I'm sending push notifications to my website users when they (for example) receive a private message. That notification goes to all browsers subscribed for that user. So could be desktop, mobile, work computer etc.

What I would like to do is close all the sent notifications once the user has a read a message.

So user logs in on mobile, reads the private message - at this point I want all the previously sent notifications for that PM to be closed/cancelled.

Is this possible?

Thanks in advance! Matt

Matt Deemer
  • 133
  • 1
  • 3
  • 9
  • Please [edit](http://stackoverflow.com/posts/43463046/edit) the question to be on-topic: include a [Minimal, Complete, and Verifiable example](http://stackoverflow.com/help/mcve) that duplicates the problem. Questions seeking debugging help ("why isn't this code working the way I want?") must include: (1) the desired behavior, (2) a specific problem or error and (3) the shortest code necessary to reproduce it in the question itself. Please also see: [What topics can I ask about here?](http://stackoverflow.com/help/on-topic), and [How to Ask](http://stackoverflow.com/help/how-to-ask) – Mr.Rebot Jul 04 '19 at 21:45
  • 2
    Hi Mr Rebot. I don't need help debugging code. I just need to know if there's any way to cancel (remotely close) web push notifications that I've already sent out. I have no code for it - I need to know if that even exists or is possible with the web push API. I cannot find anything about it online – Matt Deemer Jul 05 '19 at 07:16

1 Answers1

0

Yes this is possible, but not silently. For example, Chrome will replace the notification with a new one saying "This site has been updated in the background".

There are two separate APIs: the Push API which "gives web applications the ability to receive messages pushed to them from a server", and the Notification API which "is used to configure and display desktop notifications to the user".

The Notification API provides Notification.close(), which cancels the display of a notification.

You can use the Push API to trigger Notification.close(). Here's a sample which should go in your service worker:

self.addEventListener('push', async event => {
  const data = event.data.json();
  if (data.type === 'display_notification') {
    self.registration.showNotification(data.title, data.options);
  } else if (data.type === 'cancel_notification') {
    const notifications = await self.registration.getNotifications({
      tag: data.notificationTag
    });
    for (notification of notifications) {
      notification.close();
    }
  } else {
    console.warn("Unknown message type", event, data);
  }
});

However! This design means that your cancel_notification message won't display a notification. This violates some browser policies, for example Chrome will display a new notification saying "This site has been updated in the background".

jameshfisher
  • 34,029
  • 31
  • 121
  • 167