knaka Tech-Blog

AI, IoT, DIYエレクトロニクス, データサイエンスについて投稿予定です。

firebase Cloud Messaging + Notification APIで、Web push通知

firebase Cloud Messaging を使用して、
ブラウザにpush通知の内容となります。

環境

chrome 79 以降
webサーバ

ドメインは、localhost でも動作しました

参考のpush画面

・受信メッセージが、デスクトップに表示できました
win10ですが

f:id:knaka0209:20200115171250p:plain

準備など

firebase (firebase.google.com )
にログインし、作成したプロジェクトを開く

・Project Pverview >設定(歯車アイコン)>プロジェクトの設定

・Cloud Messaging タブ 開きます。

・サーバーキー
 トークンを、コピーしておきます。

・送信者 ID (送信時に使用)
  IDを、コピー
・鍵ペア(公開鍵)
 ウエブ設定> ウエブプッシュ証明書 、のあたり
 初回は、鍵の作成で。良かったと思います。

 鍵ペアを、コピーしておきます。

・Notification API で通知ですが、
 テストする場合。
 ブラウザの通知、許可を設定しておく必要があります。

参考のコード

github.com

実装など

ドメイン直下に、
 firebase-messaging-sw.js, manifest.json
を配置

・firebase-messaging-sw.js
 に、送信者ID を、設定

firebase.initializeApp({
  'messagingSenderId': 'YOUR-SENDER-ID'
 下記、messagingSenderId の部分
});

・受信、送信画面
https://github.com/kuc-arc-f/fcm_sample1/blob/master/test/fcm_recv2.html

・firebase 設定で、送信者ID を、設定
 下記、messagingSenderId の部分

・公開鍵、
 下記 YOUR_PUBLIC_VAPID_KEY_HERE の部分 設定

firebase.initializeApp({
   'messagingSenderId': 'YOUR-SENDER-ID'
 });
//FCM
const messaging = firebase.messaging();
messaging.usePublicVapidKey('<YOUR_PUBLIC_VAPID_KEY_HERE>');

・サーバーキー の設定
上記の、トークン追加

const FCM_SERVER_KEY = "YOUR-SERVER-KEY";

・token取得
 送信先トークンを、画面起動時に取得

    messaging.getToken().then((currentToken) => {
        if (currentToken) {
            sendTokenToServer(currentToken);
            IID_TOKEN = currentToken;
            textInstanceIdToken.value = IID_TOKEN;
//        console.log(currentToken);
        } else {
            // Show permission request.
            alert("ブラウザ通知を許可に設定下さい。メッセージを送受信できません");
            console.log('No Instance ID token available. Request permission to generate one.');
            // Show permission UI.
            updateUIForPushPermissionRequired();
            setTokenSentToServer(false);
        }
    }).catch((err) => {
        console.log('An error occurred while retrieving token. ', err);
        setTokenSentToServer(false);
    });

受信

    messaging.onMessage((payload) => {
//        console.log('Message received. ', payload);
        var notify = payload.notification;
        console.log(notify.title );
    });

送信

fetchで、送信例です
・FCM_SERVER_KEY は、上記のサーバーキー 
toは、上記で取得した。送信先 token

function test_send(){
//console.log(IID_TOKEN.length );
    var send_title = elem_title.value;
    var send_body = elem_body.value;

    if(IID_TOKEN.length < 1){ return; }
    var key = FCM_SERVER_KEY;
    var to = IID_TOKEN;
    var notification = {
        'title': send_title,
        'body': send_body,
        'icon': 'firebase-logo.png',
        'click_action': 'http://localhost'
    };

    fetch('https://fcm.googleapis.com/fcm/send', {
    'method': 'POST',
    'headers': {
        'Authorization': 'key=' + key,
        'Content-Type': 'application/json'
    },
    'body': JSON.stringify({
        'notification': notification,
        'to': to
        })
    }).then(function(response) {
//        console.log(response);
    }).catch(function(error) {
        console.error(error);
    })
};


・送信すると、firebase (firebase Cloud Messaging) 経由で
 メッセージが送信され、上記の画面のような
 push通知画面が。表示できました。