2017-05-04 3 views
0

サーバーからサービスワーカーにデータを渡そうとしていますが、サービスワーカーにデータが空になっています。ここでサーバーからサービスワーカーにデータを渡す方法

は私のコードです:

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さ:

{ 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)); 
}); 

しかし、タイトルではありません認識される。サーバーからサービスワーカーにデータを渡すにはどうすればよいですか?

答えて

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)); 

とサービス労働者に加入している間、あなたは、サブスクリプション要求を送信すると、暗号化された公開鍵を送信し、サーバからのプッシュ通知を送信するためにそれを使用する必要があります。

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); 
}); 

PS。公開鍵はサーバー側とクライアント側で同じにする必要があります。

関連する問題