LoginSignup
42
57

More than 1 year has passed since last update.

5行でわかるプッシュ通知【VAPID】

Last updated at Posted at 2022-08-02

HTMLとサービスワーカーしかない簡易なサイトを作りました。
ここに通知機能を実装してみてください😸

ソース
https://github.com/GitHub30/web-push-study

まず、サイトを開いてコンソールを出しましょう。

Chrome ( Ctrl + Shift + J )
image.png

Firefox ( Ctrl + Shift + K )
image.png

allow pasting と表示された場合は、allow pastingとキーボードで入力してください
image.png

AndroidMicrosoft EdgeSafariでも試せます。

コンソールにコードを入力し、Enterキーで実行していきましょう。

1行目 通知の許可をもらう

await Notification.requestPermission()

左上から許可するをクリックしてください
image.png
image.png

2行目 サービスワーカーを登録する

navigator.serviceWorker.register('./service-worker.js')

image.png
image.png
image.png

3行目 鍵を準備する

var applicationServerKey = 'BDd3_hVL9fZi9Ybo2UUzA284WG5FZR30_95YeZJsiApwXKpNcF1rRPF3foIiBHXRdJI2Qhumhf6_LFTeZaNndIo'

image.png

鍵を作成する場合
var vapidDetails = await fetch('https://web-push-server.vercel.app/api/generateKeys').then(r=>r.json())

Node.js、Python、OpenSSLで作ることもできます。
https://github.com/web-push-libs/web-push#generatevapidkeys
https://gist.github.com/cjies/cc014d55976db80f610cd94ccb2ab21e
https://github.com/zivver/web-push/blob/master/README.md#using-openssl

4行目 サブスクをもらう

var subscription = (await (await navigator.serviceWorker.ready).pushManager.subscribe({ userVisibleOnly: true, applicationServerKey })).toJSON()

image.png
applicationServerKeyに公開鍵を設定します。

鍵を作成した場合
var subscription = (await (await navigator.serviceWorker.ready).pushManager.subscribe({ userVisibleOnly: true, applicationServerKey: vapidDetails.publicKey })).toJSON()

5行目 プッシュ通知を送る

fetch('https://web-push-server.vercel.app/api/send', {
  method: 'POST',
  body: JSON.stringify({ subscription, payload: { title: 'やあ😸' } })
})

image.png
image.png

鍵を作成した場合
fetch('https://web-push-server.vercel.app/api/send', {
  method: 'POST',
  body: JSON.stringify({ vapidDetails, subscription, payload: { title: 'やあ😸' } })
})

作成した鍵を送ります。

Node.jsやPythonで簡単に送ることもできます。
https://github.com/web-push-libs/web-push
https://github.com/web-push-libs/pywebpush

curlで送る

copy(`curl https://web-push-server.vercel.app/api/send -d '${JSON.stringify({ subscription, payload: { title: 'やあ😸' } })}'`)
鍵を作成した場合
copy(`curl https://web-push-server.vercel.app/api/send -d '${JSON.stringify({ vapidDetails, subscription, payload: { title: 'やあ😸' } })}'`)

作成した鍵を送ります。

image.png
Networkタブのsend上でコピーすることもできます。Windowsの方はPowerShellでもよいです。

PythonやPHPに変換も可能です。

クリック時のリンクを設定する

fetch('https://web-push-server.vercel.app/api/send', {
  method: 'POST',
  body: JSON.stringify({
    subscription,
    payload: { title: 'Open Yahoo!', data: { url: 'https://www.yahoo.co.jp/' } }
  })
})

image.png

アクションボタンを作る

アクションを作ることもできます。

fetch('https://web-push-server.vercel.app/api/send', {
  method: 'POST',
  body: JSON.stringify({
    subscription,
    payload: {
      title: 'やあ😸',
      body: 'どこに行きますか?🍉',
      actions: [
        { title: 'visit Google', action: 'https://google.co.jp/' },
        { title: 'visit Mozilla', action: 'https://www.mozilla.org/' }
      ]
    }
  })
})

image.png

アイコン、優先度、振動、音を変更することもできます。

追記

上記手順をデモにしました。参考になれば幸いです。

ソース
https://github.com/GitHub30/web-push-demo

参考

https://web-push-server.vercel.app の実装
https://github.com/GitHub30/web-push-server

42
57
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
42
57