tmp
Thursday, August 16, 2018
Web Push (VAPID)
Web Push に VAPID を利用した場合の実装方法 ### generate VAPID public/private keys `generate_vapid_keys.js` ``` const webPush = require('web-push') const vapidKeys = webPush.generateVAPIDKeys() const keys = { publicKey: vapidKeys.publicKey, privateKey: vapidKeys.privateKey, } console.log(keys) ``` 生成 ``` node generate_vapid_keys.js ``` ### register service worker FCMの場合と変わらず `app.js` ``` navigator.serviceWorker.register('/sw.js') .then((registration) => { swRegistration = registration }) ``` ### subscribe `applicationServerKey` に上記で生成した公開鍵を指定 `app.js` ``` swRegistration.pushManager.subscribe({ userVisibleOnly: true, applicationServerKey: "PUBLIC_KEY" }) .then((subscription) => { // send subscription to server }) ``` ### receive push FCMの場合と変わらず `sw.js` ``` self.addEventListener('push', (e) => { console.log('[Service Worker] Push Received', e) const title = 'Title' const options = { body: e.data ? e.data.text() : 'Empty payload' } e.waitUntil(self.registration.showNotification(title, options)) }) ``` ### send push 暗号化周りが面倒なので `web-push` を利用 `'PUBLIC_KEY'`, `'PRIVATE_KEY'` にそれぞれ生成した公開鍵/秘密鍵を指定 `'SUBSCRIPTION'` は購読時に取得したものを指定 `main.js` ``` const webPush = require('web-push') const payload = 'Here is a payload!' const options = { vapidDetails: { subject: 'mailto:example_email@example.com', publicKey: 'PUBLIC_KEY', privateKey: 'PRIVATE_KEY' }, TTL: 60 } webPush.sendNotification( 'SUBSCRIPTION', payload, options ) ``` 送信 ``` node main.js ```
No comments:
Post a Comment
Newer Post
Older Post
Home
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment