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

橙三吉。 提交于 2019-12-12 02:23:21

问题


This snippet helps in either bring in the app tab in focus or open a new tab with that URL. If the tab is already open, is there a way to change the URL (based on the notification the user clicked).?

  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:


The WindowClient.navigate() method sounds like what you want. You should be able to do something like:

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


来源:https://stackoverflow.com/questions/39476963/service-worker-redirecting-a-user-to-different-url-when-he-clicks-the-notificat

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!