PWA対応 WebサイトのPUSH通知を試します。
アプリのPUSH通知のようにWEBだけでもPUSH通知は可能です。
しかし今はiosが対応していないためPCとandroidのみとなります。
PWAの基本的なところは前回の「PWA対応 Webサイトのアイコンをホーム画面に追加」を参照してください。
①プロジェクトの作成
ここで新しいプロジェクトを作成
https://console.developers.google.com
②CloudMessagingの設定
コンソール内でCloudMessagingを検索し選択
認証情報も作成
③index.htmlの変更
registration.pushManagerを追記する
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
<html> <head> <link rel="manifest" href="/manifest.json"> <script> window.addEventListener('load', function() { if ('serviceWorker' in navigator) { navigator.serviceWorker.register('/serviceWorker.js') .then(function(registration) { return registration.pushManager.getSubscription().then(function(subscription) { console.log("subscription",subscription) if (subscription) { console.log("aaa") return subscription } return registration.pushManager.subscribe({ userVisibleOnly: true }) }) }).then(function(subscription) { var endpoint = subscription.endpoint console.log("pushManager endpoint:", endpoint) }).catch(function(error) { console.log("serviceWorker error:", error) }) } })</script> </head> <body> こんにちは </body> </html> |
④manifest.jsonの変更
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
{ "name": "idealie PWA test", "short_name": "PWA test", "icons": [ { "src": "/images/icon144.png", "sizes": "144x144", "type": "image/png" } ], "start_url": "/", "display": "standalone", "theme_color": "#99d9ea", "gcm_sender_id": "xxxxxx", "gcm_user_visible_only": true } |
“gcm_sender_id”: “xxxxxx”,
“gcm_user_visible_only”: true
の部分を追記
xxxxxxはプロジェクトIDの値を使用します。
⑤serviceWorker.jsの変更
1 2 3 4 5 6 7 8 9 |
self.addEventListener("push", function(event) { console.log("event",event) event.waitUntil( self.registration.showNotification("Push title", { body: "Push test" }) ) }) |
⑥確認
https://idealive-t-pj2.tk/index.htmlのページを開くと許可を求めてきます。
許可を行うとコンソールにエンドポイントの値が取得されています。
※実際はこの値をサーバに送り、DB等に保持しておく必要があります。
curl –header “Authorization: key=apiキー” –header Content-Type:”application/json” https://fcm.googleapis.com/fcm/send -d “{\”registration_ids\”:[\”エンドポイントの値\”]}”
上記送信でプッシュできるはずなのですが、メッセージがきませんでした・・・
調べてみると今はCloudMessageではなく、Firebaseで行うのが正解のようです。
⑥Firebase設定
https://console.firebase.google.com/に接続
プロジェクトの追加を行うとCloudMessegeで使用したプロジェクトがそのまま選択できる状態になっていました。
キーの値を確認
再度送信
curl –header “Authorization: key=apiキー” –header Content-Type:”application/json” https://fcm.googleapis.com/fcm/send -d “{\”registration_ids\”:[\”エンドポイントの値\”]}”
PCの右下あたりにプッシュでました。
少しひっかかりましたが、なんとかプッシュできました。
以上です。
“PWA対応 WebサイトのPUSH通知” への 0 件のフィードバック