5. Service Workerを作成
Webプッシュを受信するためにはService Workerが必要です。push
とnotificationclick
のイベントリスナーを追加します。
public/service-worker.js
addEventListener('push', (event) => {
console.log('[Service Worker] Push Received.');
console.log(`[Service Worker] Push had this data: "${event}"`);
if (!(self.Notification && self.Notification.permission === 'granted'))
return;
var data = {};
if (event.data)
data = event.data.json();
console.log(data)
var title = data.data['pinpoint.notification.title'];
var message = data.data['pinpoint.notification.body'];
var icon = data.data['pinpoint.notification.imageIconUrl'];
var image = data.data['pinpoint.notification.imageUrl'];
var options = {
body: message,
icon: icon,
image: image,
data: data
};
event.waitUntil(self.registration.showNotification(title, options));
});
addEventListener('notificationclick', (event) => {
console.log('[Service Worker] Notification click: ', event);
event.notification.close();
event.waitUntil(
clients.openWindow(event.notification.data.data['pinpoint.url'])
);
});