Push-уведомления с работником службы не отображаются в браузере - PullRequest
0 голосов
/ 11 марта 2019

Я последовал примеру здесь , чтобы интегрировать Push API в мое прогрессивное веб-приложение.Я не могу увидеть уведомление, отправленное с сервера.На вкладке «Сеть» я вижу, что ответ сервера был успешно отправлен (201), но событие «push» для работника службы никогда не запускается.Я в основном тестирую в Chrome, но также проверил Firefox, чтобы убедиться, что это не зависит от браузера.

Вот мой код:

/**
* MYCOMPONENT.JS
*/
class MyComponent extends Component {
  constructor(props) {
    super(props);
  }

  sendNotification = () => {
    const subJSON = JSON.stringify({
      subscription: window.subscription
    });
    return fetch('./sendNotification', {
      method: 'post',
      headers: {
        'Accept': 'application/json, text/plain, */*',
        'Content-type': 'application/json'
      },
      body: subJSON,
    });
  }

  render() {
    return (
      <div className="container">
        <div><Button onClick={this.sendNotification} className="item">Get Server Notifications</Button></div>
      </div>
    );
  }
}

export default MyComponent;

/**
* INDEX.JS
*/
navigator.serviceWorker.ready
.then(function(registration) {
  return registration.pushManager.getSubscription()
  .then(async function(subscription) {
    alert('.');
    if (subscription) {
      return subscription;
    }
 
    const response = await fetch('./vapidKey');
    const vapidPublicKey = await response.text();
    const convertedVapidKey = urlBase64ToUint8Array(vapidPublicKey);
 
    return registration.pushManager.subscribe({
      userVisibleOnly: true,
      applicationServerKey: convertedVapidKey
    });
  });
}).then(function(subscription) {
  window.subscription = subscription;
  fetch('./register', {
    method: 'post',
    headers: {
      'Content-type': 'application/json'
    },
    body: JSON.stringify({
      subscription: subscription
    }),
  });

  document.getElementById('doIt').onclick = function() {
    const delay = 1;
    const ttl = 0;
    fetch('./sendNotification', {
      method: 'post',
      headers: {
        'Content-type': 'application/json'
      },
      body: JSON.stringify({
        subscription: window.subscription,
        delay: delay,
        ttl: ttl,
      }),
    });
  };
});

/**
* SERVICE WORKER PUSH LISTENER
*/
window.self.addEventListener('push', function(event) {
  alert('service worker push'); //NEVER ALERTS, THIS LISTENER IS NOT FIRED
  const payload = event.data ? event.data.text() : 'no payload';

  event.waitUntil(
    window.self.registration.showNotification('Executive Experience', {
      body: payload,
    })
  );
});

/**
* SERVER.JS
*/
process.env.VAPID_PRIVATE_KEY = //MY HARDCODED VAPID PRIVATE KEY;
process.env.VAPID_PUBLIC_KEY = //MY HARDCODED VAPID PUBLIC KEY

webPush.setVapidDetails(
  'https://serviceworke.rs/',
  process.env.VAPID_PUBLIC_KEY,
  process.env.VAPID_PRIVATE_KEY
);

app.get('/vapidKey', function(req, res) {
  console.log('vapid fetch');
  res.send(process.env.VAPID_PUBLIC_KEY);
});

app.post('/register', function(req, res) {
  res.sendStatus(201);
});

app.post('/sendNotification', jsonParser, function(req, res) {
  const subscription = req.body.subscription;
  const payload = null;
  const options = {
    TTL: req.body.ttl
  };

  setTimeout(function() {
    webPush.sendNotification(subscription, payload, options)
    .then(function() {
      res.sendStatus(201);
    })
    .catch(function(error) {
      res.sendStatus(500);
      console.log(error);
    });
  }, req.body.delay * 1000);
});
...