如何解决Service Worker导航错误“This service worker is not the client's active service worker”?

5
我已经为我的 quasar pwa 创建了一个服务工作者来管理 fcm web 后台通知。目的是管理前台和后台通知的点击,并将用户重定向到我的 pwa 的特定页面。
所以当我收到通知时,有两种情况:
前台通知:
1a) 浏览器聚焦/最大化 + 用户已经在 pwa 标签页上 + pwa 在正确的页面上 -> 无需操作
1b) 浏览器聚焦/最大化 + 用户已经在 pwa 标签页上 + pwa 在其他页面上 -> 我需要重定向到特定的 pwa 页面
后台通知:
2a) 浏览器未聚焦或最小化或用户不在 pwa 标签页上 + pwa 在正确的页面上 -> 我需要聚焦/最大化浏览器或聚焦 pwa 标签页,然后无需操作
2b) 浏览器未聚焦或最小化或用户不在 pwa 标签页上 + pwa 在其他页面上 -> 我需要聚焦/最大化浏览器或聚焦 pwa 标签页,然后重定向到特定的 pwa 页面

在1a、1b和2a中一切正常。在2b中,我遇到了奇怪的错误“This service worker is not the client's active service worker”。

我在服务工作者中有以下代码来管理后台通知点击的重定向。并且我在navigate()方法上遇到了错误。

self.addEventListener('notificationclick', function(event) {
    console.log('notificationclick', event);
    event.notification.close();

    let route = event.notification.data.route ? JSON.parse(event.notification.data.route) : null;
    if(route && route.params && route.params.token) {
      const domain = route.domain;
      const path = '/#/' + route.name + '/' + route.params.token;
      const fullUrl = domain + path

      event.waitUntil(clients.claim().then(() => {
          return clients.matchAll({
            type: 'window',
            includeUncontrolled: true
          })
          .then(clients => clients.filter(client => client.url.indexOf(domain) !== -1))
            .then(matchingClients => {
              if (matchingClients[0]) {
                return matchingClients[0].focus().then(function (client) {
                  client.navigate(path)
                    .then(client => {
                    }).catch(function (e) {
                    console.log(e); --> here I get the error
                  });
                }).catch(function (e) {
                  console.log(e);
                });
              }

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

我在网上搜索了这个错误,但没有找到任何参考资料,所以我不理解这个错误,也无法解决它。请问有人可以帮忙吗? 谢谢。


也许这个问题/答案可以帮到你?https://dev59.com/Y5zha4cB1Zd3GeqPF3xF#40635515 - Stef Chäser
谢谢,但我已经尝试在matchAll方法中删除includeUncontrolled,但它不起作用:SW始终会打开一个新标签页。 - nulele
我也遇到了同样的问题。我可以将当前标签置于焦点,或者从通知中打开一个新的带有新 URL 的标签页,但我无法让它在当前标签页中打开新的 URL。 - fromage9747
1个回答

5

无论我尝试什么,使用client.navigate(path)都没能让它正常工作...在GitHub、MDN文档等地方搜索了几个小时后,我最终使用了client.postMessage()接口。

请将上面的代码替换为以下内容:

client.postMessage({
  action: 'redirect-from-notificationclick',
  url: path,
})

今日免费次数已满, 请开通会员/明日再来
// Listen to service worker messages sent via postMessage()
navigator.serviceWorker.addEventListener('message', (event) => {
  if (!event.data.action) {
    return
  }

  switch (event.data.action) {
    case 'redirect-from-notificationclick':
      window.location.href = event.data.url
      break
    // no default
  }
})

这个很好用,谢谢! - Yuniac

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接