Firebase Cloud Messaging Service Worker redirection in Chrome

Viewed 1059

I have a Service Worker of firebase messaging with this listener:

self.addEventListener('notificationclick', function(event) {
  const url = dispatchNotification(event.notification.data);
  event.notification.close();
  const appUrl = `${url}`;
  event.waitUntil(clients.matchAll({
          type: 'window',
          includeUncontrolled: true
      }).then( activeClients => {
          if (activeClients.length > 0) {
              activeClients[0].navigate(appUrl).then(client => client.focus());
          } else {
              clients.openWindow(appUrl);
          }
      })
  );
});

In Firefox the redirection works perfectly, but in chrome it throw's a error like this:

Uncaught (in promise) TypeError: Cannot navigate to URL: http://localhost:4100/urlParams

Any idea why it can works perfectly fine in firefox and throw the error in chrome? localhost it's a secure url so can't be the ssl restriction.

The notification is showed correctly the only problem is the redirection to the tab.

1 Answers

This is an old question but I'll try to take a crack at answering it. I can only give a partial answer at the moment and hope to be able to update you once I find the entire solution.

I currently have the same issue. When I use the firebase-messaging-sw.js file as my only service worker and try to open a client (in the sense of a client belonging to the client API), it says that it is not the client's active service worker.

screen of console in Chrome showing firebase-messaging-sw error

That error gives you a hint at what is going wrong.

You have to add your own custom service worker to be able to redirect the user to the right view. You can do this by doing the following in your main JavaScript file:

if ('serviceWorker' in navigator) {
  navigator.serviceWorker.register('./sw.js')
           .then(registration => {
             messaging.useServiceWorker(registration);
           })
           .catch(err => console.error(`Error while registering service worker: ${err}`));
}

This is assuming your custom service worker is named sw.js and is at the root of your domain folder.

Unfortunately, I can't get my service worker and firebase-messaging-sw to communicate at the moment since I'm trying to do custom push events but hopefully this will get you started in the right direction.

Update

I finally got it working on my end but it might not work for your problem. It depends on what kind of architecture you have. If you're serving your resources via Firebase or via a Single-Page Application, it might require a different solution to what I found.

In my case I have a Multi-Page Application and each file is served directly from the server. I had a bad url in a switch statement that meant that the file was never 'served'. When the user clicked on the notification, the service worker couldn't find the right page and ended up always opening the default page.

Related