sw-precache服务工作者推送通知未在create-react-app中首次收到

时间:2019-03-21 14:55:21

标签: reactjs push-notification service-worker create-react-app sw-precache

我正在使用CRA,并尝试在生产环境中使用sw-precache使用自定义服务工作程序。但是即使允许,也无法发送接收通知。当我重新加载页面并再次允许接收通知的权限时,我正在接收通知。这是在我第一次在新的浏览器/系统上打开Web应用程序时发生的。 有人可以帮我吗?

这是我的自定义服务工作者的样子:(sw.js)


var url = '';
self.addEventListener('push', function(event) {
  if (!(self.Notification && self.Notification.permission === 'granted')) {
    return;
  }
  var matchingClient = null;
  url = '';
  event.waitUntil(
    self.clients
      .matchAll({
        type: 'window',
        includeUncontrolled: true,
      })
      .then(windowClients => {
        let data = {};
        if (event.data) {
          data = event.data.json();
        }
        url = data.action;
        for (let i = 0; i < windowClients.length; i++) {
          const windowClient = windowClients[i];
          if (windowClient.url === url && windowClient.focused === true) {
            matchingClient = url;
            break;
          }
        }
        if (!matchingClient) {
          return self.registration.showNotification(data.title, {
            body: data.body,
            icon: 'logo.png',
          });
        }
      }),
  );
});

self.addEventListener('notificationclick', function(event) {
  event.notification.close();
  var client = null;
  event.waitUntil(
    self.clients
      .matchAll({
        type: 'window',
        includeUncontrolled: true,
      })
      .then(windowClients => {
        for (let i = 0; i < windowClients.length; i++) {
          const windowClient = windowClients[i];
          if (windowClient.url === event.target.url) {
            client = windowClient;
            break;
          }
        }
        if (!client) {
          return self.clients.openWindow(event.target.url);
        } else {
          return client.focus();
        }
      }),
  );
});

这是sw-precache配置文件:

module.exports = {
  staticFileGlobs: ['build/static/css/**.css', 'build/static/js/**.js'],
  swFilePath: './build/service-worker.js',
  stripPrefix: 'build/',
  importScripts: ['./sw.js'],
  handleFetch: false,
};

0 个答案:

没有答案