1
0

More than 3 years have passed since last update.

firebaseのプッシュ通知 adventcalender 2019-12-07

Last updated at Posted at 2020-01-21

push通知

Webサービスであるあるな機能ですが、ポートフォリオにはプッシュ通知の
サンプルデモっぽいのがないなーと思って作ることにしました

システム構成

フロントページ firebase
バックエンド google cloud platform
SDKバージョン 8.6.3

今回の完成イメージ図

今回は、GCP内にサイトを配置して、GCPの機能で送信するようにしました

スクリーンショット 2021-05-30 183454.png

最終的な成果物URL

実装の解説

基本としては、以下の公式サイトを見ながら進めます

完成形

ディレクトリ構成
今回は、バックグラウンドでの通知を取得する部分と表示するページを用意しました

サイトページ

       // firebase.messaging()を呼び出すときは、appIdを設定しておくこと
       const firebaseConfig ={
        apiKey: "AIzaSyBKRl.....Y9rrbvMBkA",
        authDomain: "PROJECT_ID.firebaseapp.com",
        projectId: "PROJECT_ID",
        storageBucket: "....",
        messagingSenderId: ".....",
        appId: "....",
        measurementId: "......"
      };
      // firebaseのsdkを使えるように初期化
      firebase.initializeApp(firebaseConfig);

      // Retrieve an instance of Firebase Messaging so that it can handle background
      const messaging = firebase.messaging();
      // 送信先としてのトークン設定
      messaging.getToken({ vapidKey: 'BL9LaayZOeYBIArkEUkXi8sH8SWlLZ3_C4sGFLG91n_BEUyhR5LcHU3fqjYT8ADeHJE7cgpEAT2QD7bKzhraFvs' }).then((currentToken) => {
        if (currentToken) {
          // Send the token to your server and update the UI if necessary
          // ...
        } else {
          // Show permission request UI
          console.log('No registration token available. Request permission to generate one.');
          // ...
        }
      }).catch((err) => {
        console.log('An error occurred while retrieving token. ', err);
        // ...
      });

firebase-messaging-sw.js

  // firebase sdk import index.htmlとバージョンをそろえる
  importScripts('https://www.gstatic.com/firebasejs/8.6.3/firebase-app.js');
  importScripts('https://www.gstatic.com/firebasejs/8.6.3/firebase-messaging.js');

  const firebaseConfig ={
        apiKey: "AIzaSyBKRl.....Y9rrbvMBkA",
        authDomain: "PROJECT_ID.firebaseapp.com",
        projectId: "PROJECT_ID",
        storageBucket: "....",
        messagingSenderId: ".....",
        appId: "....",
        measurementId: "......"
  };
  firebase.initializeApp(firebaseConfig);

  // Retrieve an instance of Firebase Messaging so that it can handle background
  const messaging = firebase.messaging();

  // Get registration token. Initially this makes a network call, once retrieved
  // サイトを閉じているときにpush通知を受信
  messaging.onBackgroundMessage((payload) => {
      console.log('[firebase-messaging-sw.js] Received background message ', payload);
      // Customize notification here
      const notificationTitle = 'advent 通知チャレンジ完了';
      const notificationOptions = {
            body: '',
            icon: '/firebase-logo.png'
      };

      self.registration.showNotification(notificationTitle,
      notificationOptions);
  });

JavaScript側での通知受け取り部分

push通知_ディレクトリ解説.png

実際に投稿してみた

実装したので、cloud messagingから投稿をしてみる

感想

今回は実際にcloudmessagingように投稿したサイトとして通知が出てくるところまで試せてよかった。
Webデザインをもう少し整えたら、製品の体験まではサーバーの実装はなしでもやれそうだなという印象。

利用資料

公式の以下URLから、完成イメージのアイコンは利用させていただきました

1
0
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
1
0