How to prevent showing unclickable web push notifications - firefox

105 Views Asked by At

I've implemented a service worker that fully served web push notifications on my app.

However, I've found a bug when using firefox in incognito mode.

On MacOS, I am able to quit the "main" window (not in incognito) but keep working on another incognito window.

When doing so, my service worker keep receive "push" event that leads to showing a notification.

When I click on the notification, nothing happens, because my call to self.clients.openWindow() throws an error, because there is no window visible for the current service worker.

I'd like to detect this configuration before showing the notification, either for not showing it or append an explicit message about the situation.

Here is my "notificationclick" handler:

self.addEventListener('notificationclick', async (event) => {
  const {
    data: {
      community: {
        id: communityId,
      },
      project: {
        code: projectCode,
      },
      news: {
        id: newsId,
      },
    },
  } = event.notification.data;
  const commentId = event.notification.data.data?.comment?.id;
  const url = `https://${self.location.hostname}/project/${projectCode}/community/${communityId}/news/${newsId}?referrer=pushBrowser${commentId ? `&commentId=${commentId}` : ''}`;
  // eslint-disable-next-line no-param-reassign
  gNotificationsStatus.set(event.notification.tag, { clicked: true });
  event.notification.close(); // Android needs explicit close.
  event.waitUntil((async () => {
    await logEvent(
      EVENTS.NOTIF_CLICKED,
      computeNotifEventPayload(event.notification.data, EVENT_DESTINATION.AMPLITUDE),
      computeNotifEventPayload(event.notification.data, EVENT_DESTINATION.MS),
    );
    console.log('checking opened tabs');
    const windowClients = await self.clients.matchAll({ type: 'window' });
    // Check if there is already a window/tab open with the target URL
    for (let i = 0; i < windowClients.length; i += 1) {
      const client = windowClients[i];
      // If so, just focus it.
      if (client.url === url
        && 'focus' in client) {
        client.focus();
      }
    }
    // If not, then open the target URL in a new window/tab.
    console.log('opening window to', url);
    if (self.clients.openWindow) {
      try {
       const client = await self.clients.openWindow(url);
       client.focus();
      } catch (err) {
        console.log(err);
      }
    }
  })());
});

I've tested on Google Chrome and it is able to open the window

Safari encounters the same problem that firefox

0

There are 0 best solutions below