首页 > 解决方案 > 通知中的 Serviceworkerglobalcontext.onnotificationclick 和振动选项在 React.js 中不会触发

问题描述

我在 MERN 应用程序中使用服务人员推送通知。push 事件和 onclick 事件的代码如下所示。

self.onnotificationclick = (e) => {
  e.notification.close(); // Android needs explicit close.
  e.waitUntil(
    clients
      .matchAll({ includeUncontrolled: true, type: "window" })
      .then((clientsArr) => {
        // If a Window tab matching the targeted URL already exists, focus that;
        const hadWindowToFocus = clientsArr.some((windowClient) =>
          windowClient.url ===
          `${self.location.origin + e.notification.data.url}`
            ? (windowClient.focus(), true)
            : false
        );
        // Otherwise, open a new tab to the applicable URL and focus it.
        if (!hadWindowToFocus)
          clients
            .openWindow(`${self.location.origin + e.notification.data.url}`)
            .then((windowClient) =>
              windowClient ? windowClient.focus() : null
            );
      })
  );
};

self.addEventListener("push", (event) => {
  console.log(event);
  const data = event.data.json();
  console.log("New notification", data);
  const options = {
    body: data.body,
    icon: data.icon,
    vibrate: [300, 100, 400],
    data: { url: data.url },
    action: [{ type: "open_url" }],
  };
  event.waitUntil(self.registration.showNotification(data.title, options));
});

在 onclick 函数中,我检查页面是否打开,如果没有打开一个新页面,这在开发模式下工作正常,但是当我将它部署到 heroku 时,通知点击没有做任何事情。showNotification 函数中的振动选项也不起作用。

标签: reactjsexpresspush-notificationservice-workerweb-push

解决方案


推荐阅读