服务人员NotificationClick事件未聚焦或在选项卡中打开我的网站

San*_*dro 2 javascript firebase reactjs service-worker service-worker-events

我在我的网站中使用FCM推送通知,我希望用户在他或她单击推送通知时可以进入我的网站。请注意,该用户可能在其他应用程序中或在其他浏览器选项卡中,并且我希望当用户收到fcm通知时,通过在Firefox浏览器中单击该通知将能够进入我的网站。因此,我使用了在service worker中可用的notificationclick事件。我使用的代码是这样的:

self.addEventListener('notificationclick', event => {
  console.log('On notification click: ', event.notification.tag);
  event.notification.close();

  // This looks to see if the current is already open and
  // focuses if it is
  event.waitUntil(
    clients
      .matchAll({
        type: 'window'
      })
      .then(clientList => {
        for (let i = 0; i < clientList.length; i++) {
          const client = clientList[i];
          if (client.url === '/' && 'focus' in client) return client.focus();
        }
        if (clients.openWindow) return clients.openWindow('/');
      })
  );
});
Run Code Online (Sandbox Code Playgroud)

它没有打开窗口,也没有关注我的网站标签。为了调试代码,我打印了clientList变量,它是一个零长度的数组。

我在浏览器中得到的错误是

On notification click: 
InvalidStateError: An attempt was made to use an object that is not, or is no longer, usable firebase-messaging-sw.js:92
Run Code Online (Sandbox Code Playgroud)

上面的错误涉及以下代码行:

event.waitUntil(
Run Code Online (Sandbox Code Playgroud)

操作系统:Mac firefox:63.0.3 reactjs:16.2.0

小智 7

使用notificationclick之前将您的处理程序移到代码行之前messaging = firebase.messaging();。FCM JS SDK安装了自己的全局notificationclick处理程序,并且其e.waitUntil()调用设法(以某种方式)中断了Firefox事件对象。如果您先安装全局处理程序,那么它将首先被调用,因此它将真正起作用。但是,它可能会以某种晦涩的方式破坏FCM处理程序。

IMO,这是Firefox本身的错误,与服务工作者而不是FCM有关,但FCM无疑是造成此问题的原因。

相关:

https://github.com/firebase/quickstart-js/issues/282(相同的FCM错误)

https://bugzilla.mozilla.org/show_bug.cgi?id=1468935(相同的FCM + Firefox错误,错误修复)

https://bugzilla.mozilla.org/show_bug.cgi?id=1313096(Firefox开发团队无法在其Service Worker测试套件中测试回调的方法,这使Firefox的这一部分易于发现错误)

https://bugzilla.mozilla.org/show_bug.cgi?id=1489800(相同的浏览器错误,其他产品)