在浏览器中未显示带有服务人员的推送通知

时间:2019-03-11 14:22:12

标签: reactjs service-worker progressive-web-apps push-api service-worker-events

我遵循了here中的示例,将Push API集成到了我的渐进式Web应用程序中。我看不到服务器发送的通知。我可以在“网络”选项卡中看到服务器的响应已成功发送(201),但是永远不会触发服务工作者上的“推送”事件。我主要在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);
});

0 个答案:

没有答案
相关问题