2

I am building a system to send web push notifications with chrome. When someone receives my push notification on their desktop PC they see the notification for about 10 seconds. If they don't click on the notification it will then disappear after about 10 seconds.

I see other websites sending push notifications that do not disappear. I believe there is some setting I am not using to make my messages stay on the screen until clicked or exited. Does anyone know this setting or parameter?

user3928082
  • 113
  • 1
  • 8

2 Answers2

2

It looks like you need to use the 'requireInteraction' option creating the notification in your service worker. Just set it to 'true' to say the browser you need the user interaction. Here is how you do this.

...in your service worker script when you create a notification:

self.addEventListener('push', function(e) {
    var notification = self.registration.showNotification(
        "Hi! Click me!",
        {
            requireInteraction: true,
            body: "I'm not going to disappear"
        }
    );
    e.waitUntil(notification);
});

Also don't forget to close it on click event:

...later in the service worker script:

self.addEventListener('notificationclick', function(e) {
    e.preventDefault();
    e.notification.close();

    // Do click actions
});

Browser comparability: unfortunately not everybody supports this option yet: Firefox doesn't. See the Mozilla reference for details: https://developer.mozilla.org/en-US/docs/Web/API/notification/requireInteraction

But it works fine in Chrome.

Sergey
  • 83
  • 1
  • 8
0

You may want to try the suggested solution in this SO post which consists the following steps:

  1. Register listeners for all the events mentioned in chrome.notifications.
  2. Register a timeout after a few seconds (e.g. 30) -after the notification is hidden- that will delete and re-create the notification (so it effectively stays visible on the screen.
  3. If any of the listeners set on step 1 fires, it means the user interracted with the notification, so cancel the timeout (you don't need to re-create the notification).

See the post for more information.

Community
  • 1
  • 1
Teyam
  • 7,686
  • 3
  • 15
  • 22