Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why isn't the 'notificationclick' event called on iOS during PWA push notifications?

I'm testing with simple-push-demo. Everything works fine, but the "notificationclick" event is not called. This works fine in desktop browsers. The problem is the iphone.

It is called when the notification is clicked while the PWA app is terminated. However, it doesn't get called when it's running or in the background.

The test environment is iOS 16.5. Anyone with good ideas, please advise.

self.addEventListener('push', function(event) {
    console.log('Push message received.');
    let notificationTitle = 'Hello';
    const notificationOptions = {
        body: 'Thanks for sending this push msg.',
        icon: './images/logo-192x192.png',
        badge: './images/badge-72x72.png',
        data: {
            url: 'https://web.dev/push-notifications-overview/',
        },
    };

    if (event.data) {
        const dataText = event.data.text();
        notificationTitle = 'Received Payload';
        notificationOptions.body = `Push data: '${dataText}'`;
    }

    event.waitUntil(
        self.registration.showNotification(
            notificationTitle,
            notificationOptions,
        ),
    );
});

self.addEventListener('notificationclick', function(event) {
    console.log('Notification clicked.');
    event.notification.close();

    let clickResponsePromise = Promise.resolve();
    if (event.notification.data && event.notification.data.url) {
        clickResponsePromise = clients.openWindow(event.notification.data.url);
    }

    event.waitUntil(clickResponsePromise);
});

I think I've done them all. ㅠㅠ

like image 329
Hoyeon Choi Avatar asked Jan 23 '26 12:01

Hoyeon Choi


1 Answers

I was having the same issue, then I try putting event.preventDefault() and worked. My notificationclick event looked like this:

self.addEventListener("notificationclick", (event) => {
  event.preventDefault();

  let distUrl = self.location.origin + "/specific-path";
  const apntId = event.notification.data?.apntId;
  if (apntId) distUrl = self.location.origin + "/other-path/" + apntId;

  event.notification.close();

  event.waitUntil(
    self.clients.matchAll({ type: "window", includeUncontrolled: true }).then((clients) => {
      if (clients.length > 0) {
        const client = clients[0];
        client.navigate(distUrl);
        client.focus();
        return;
      } else event.waitUntil(self.clients.openWindow(distUrl));
    })
  );
});
like image 100
Dariel Arian Acosta Campos Avatar answered Jan 27 '26 00:01

Dariel Arian Acosta Campos



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!