LoginSignup
3
2

More than 3 years have passed since last update.

Web Push Notification のサンプル

Last updated at Posted at 2019-05-29

まずは、次のコードを実行します。
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 にアクセスし次のボタンをクリックします。

Register ServiceWorker
Start Subscribe
Send Push
webpush_may3001.png

次に 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 の変更により、表示されるメッセージが変わります。

3
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
2