服务工作者:在用户单击通知时将用户重定向到其他URL

时间:2016-09-13 18:42:23

标签: javascript service-worker web-push

此代码段有助于将应用程序选项卡置于焦点或使用该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');
      }
  })
  );

1 个答案:

答案 0 :(得分:5)

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);
    })
);