まずは、次のコードを実行します。
Web Push Notification Sample for both Server and Client
git clone https://github.com/otiai10/web-push-notification-sample
cd web-push-notification-sample
npm install
node server.js
ブラウザーで http://localhost'8080 にアクセスし次のボタンをクリックします。
次に server.js の trigger: の部分を次のように改造してみます。
server.js
(省略)
trigger: (req, res) => {
message_aa = `皆さん こんにちは。 `
const icon = `img/${Math.floor(Math.random() * 3)}.png`;
const params = {
title: "You've got a push-notification!!",
msg: message_aa + `Hi, this is message from server. It"s ${new Date().toLocaleString()} now. You can send any message, e.g. notification icons and so`,
icon: icon,
};
Promise.all(subscribers.map(subscription => {
return webpush.sendNotification(subscription, JSON.stringify(params), {});
})).then(res => console.log(res)).catch(err => console.log('ERROR', err));
},
};
(省略)
再び、サーバーを起動し、ブラウザーでアクセスします。
server.js の変更により、表示されるメッセージが変わります。