【问题标题】:How to pass data from server to service worker如何将数据从服务器传递到服务人员
【发布时间】:2017-05-04 13:08:09
【问题描述】:

我正在尝试将数据从我的服务器传递给服务工作人员,但服务工作人员的数据是空的。

这是我的代码:

var webpush = require('web-push');
var message = sendData.message;
var subscription_info = sendData.subscription_info;




webpush.setVapidDetails(
  'mailto:xxx',
  public_key,
  private_key
);

webpush.setGCMAPIKey('xxx');
webpush.sendNotification(subscription_info, String(message));

这是 console.log(message):

{ text: 'message',
  title: 'title',
  icon_image: 'http://google.com/xxx.jpg',
  link: 'www.google.com' }

这是我的服务人员:

self.addEventListener('push', function(event) {

  var title = event.data.title;
  var options = {
    body: event.data.text,
    requireInteraction: true
  };

  event.waitUntil(self.registration.showNotification(title, options));
});

但无法识别标题。如何将数据从我的服务器传递给 service worker?

【问题讨论】:

    标签: javascript service-worker


    【解决方案1】:

    在 NodeJS 端尝试以下代码。您缺少将 JSON 消息对象转换为 Buffer(二进制)。

    var webpush = require('web-push');
    var message = sendData.message;
    var subscription_info = sendData.subscription_info;
    
    webpush.setVapidDetails(
      'mailto:xxx',
      <Vapid public key>,
      <Vapid private key>
    );
    
    webpush.setGCMAPIKey('xxx');
    message = new Buffer.from(JSON.stringify(message)); // missing code.
    webpush.sendNotification(subscription_info, String(message));
    

    并且在订阅时在 Service Worker 中,您需要在发送订阅请求时发送加密的公钥,并使用它从服务器发送推送通知。

    const vapidPublicKey = '<Vapid public key>';
    const convertedVapidKey = urlBase64ToUint8Array(vapidPublicKey);
    
    registration.pushManager.subscribe({
        userVisibleOnly: true, //Always show notification when received
        applicationServerKey: convertedVapidKey
    })
    .then(function (subscription) {
        console.log(subscription) // use this subscription info on server side
        console.info('Push notification subscribed.');
    })
    .catch(function (error) {
        console.error('Push notification subscription error: ', error);
    });
    

    附言。您的公钥在服务器端和客户端应该相同。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-03-23
      • 1970-01-01
      • 2016-02-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-01-19
      相关资源
      最近更新 更多