Martin Andersen
Martin Andersen

Reputation: 2740

How to make a web push notification stay open

I am trying to make a push notification stay open until a user interacts with it.

Have downloaded The Blazzing Pizza example. The app is using push notification.
I added:

requireInteraction: true

to the config

service-worker.js

self.addEventListener('install', async event => {
    console.log('Installing service worker...');
    self.skipWaiting();
});

self.addEventListener('fetch', event => {
    // You can add custom logic here for controlling whether to use cached data if offline, etc.
    // The following line opts out, so requests go directly to the network as usual.
    return null;
});

self.addEventListener('push', event => {
    const payload = event.data.json();
    event.waitUntil(
        self.registration.showNotification('Blazing Pizza', {
            body: payload.message,
            icon: 'img/icon-512.png',
            vibrate: [100, 50, 100],
            requireInteraction: true,
            data: { url: payload.url }
        })
    );
});

self.addEventListener('notificationclick', event => {
    event.notification.close();
    event.waitUntil(clients.openWindow(event.notification.data.url));
});

It's not working. After 20 seconds the alert disappears.

Found a very good article about notification. Named "Notification behavior"

It only has to work on windows 10 and 11. With latest Edge and chrome

Update: I found this site with examples on different push notifications. requireInteraction also not working there.

But it works in Chrome. Chrome is showing a close button on the notification when requireInteraction is true.

Upvotes: 0

Views: 419

Answers (1)

Kendrick Li
Kendrick Li

Reputation: 3106

requireInteraction: true should and does work on my device (Windows 10, Edge version 110.0.1587.50, same Blazing Pizza). The notification will not disappear unless I manually close it. You may have to rebuild the whole program and test again.

UPDATE

It looks like the notification auto-dismissing after 25 seconds is now by design and is an expected behavior in Microsoft Edge due to users' feedback. You can find more information here. The reason why my previous test shows a different behavior seems to be that I was calling Microsoft Edge directly from Visual Studio, which works in a different way from my "normal" Microsoft Edge. Now I've tested the Blazing Pizza again in the normal one but the notification auto-dismisses this time after 25 seconds. Of course, the latest push notifications sample you've provided shows the same behavior. Edge auto-dismisses but Chrome persists.

Upvotes: 3

Related Questions