Focus tab and change page with service worker

1.2k views Asked by At

We need a little help with a service worker. What we want to do is to click on notification, to execute service worker code and to check if the site is yet opened in a tab: if the site is not opened, we want to open a new tab and to navigate to a predefined url, if it is opened, we want to focus tab and then to navigate to a predefined path of the site.

We tried the code below but it doesn't work, cause we get some errors such as 'the service worker is not the active one' and so on.

Any help is really appreciated

Thanks

event.waitUntil(clients.matchAll({type: 'window' }).then(function (clientList) {

      let openNewWindow = true;
      for (let i = 0; i < clientList.length; i++) {
        const client = clientList[i];
        if (client.url.includes('localhost') && 'focus' in client) {
          openNewWindow = false;
          client.focus()
                 .then(function (client2)
                 { return client.navigate(openUrl)});
         // });
        }
      }
      if (openNewWindow) {
        return clients.openWindow(openUrl);
      }

    }));
1

There are 1 answers

0
Archer On

I don't know if you still need a solution, but we did it like this.
After click, we look for the right registration by a lookup. Because our solution has many different customers, and there can be multiple registrations. When we found it, we send a message. Somewhere else we have a listener on those messages to handle the rounting with the angular app.

If there is no tab opened, we use winClients.openWindow(url)

self.addEventListener('notificationclick', event => handleClick (event));

const handleClick = async (event) => {
  const data = event.notification.data
  const winClients = clients;
  const action = event.action;
  event.notification.close();
  event.waitUntil(
    clients.matchAll({includeUncontrolled: true, type: 'window'}).then(clients => {
      let found = false;
      let url = data.fallback_url;

      if (action === 'settings') {
        url = data.actions.settings;
      }

      clients.every(client => {
        if (client.url.includes(data.lookup)) {
          found = true;
          client.focus(); 
          client.postMessage({action: 'NOTIFICATION_CLICK', message_id: data.message_id, navigate_url: url});
          return false;
        }
        return true;
      });

      if (!found) {
        winClients.openWindow(url);
      }
    })
  );
};