Service Worker:当用户点击通知时将用户重定向到不同的 url

Service worker: Redirecting a user to different url when he clicks the notification

此代码段有助于使应用标签成为焦点或使用该标签打开新标签 URL。如果选项卡已经打开,是否可以更改 URL(基于用户单击的通知)。?

  event.waitUntil(
  clients.matchAll({
      type: 'window'
  })
  .then(function(windowClients) {
      for (var i = 0; i < windowClients.length; i++) {
          var client = windowClients[i];
          if (url.test(client.url) && 'focus' in client) {
              return client.focus();
          }
      }
      if (clients.openWindow) {
          return clients.openWindow('/#/chat');
      }
  })
  );

WindowClient.navigate() 方法听起来像您想要的。您应该能够执行以下操作:

// Assume that you want to find the first window that is currently open
// to originalUrl, and navigate that window to navigationUrl.
// If there is no window currently at originalUrl, then open a new window.
event.waitUntil(
  clients.matchAll({type: 'window'})
    .then(clients => clients.filter(client => client.url === originalUrl))
    .then(matchingClients => {
      if (matchingClients[0]) {
        return matchingClients[0].navigate(navigationUrl)
                 .then(client => client.focus());
      }

      return clients.openWindow(navigationUrl);
    })
);