Firebase Cloud Messaging for Web

Sarinthon Mangkorn-ngam
3 min readOct 5, 2020

--

ด้วย Firebase Cloud Messaging (FCM) รองรับการส่ง Notification ไปยัง iOS, Android, Web, C++ และ Unity ทำให้เราสามารถใช้ FCM ส่ง Notification เข้ามายัง Website ของเราได้ผ่านซึ่ง Web browser ที่รองรับมีดังนี้

จากรูปจะเห็นได้ว่า FCM รองรับ Microsoft Edge 17+, Firefox and Google Chrome

Set up a JavaScript Client

ก่อนอื่นเลยให้สร้างไฟล์ index.html ขึ้นมาและเขียน Code ดังนี้

<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Document</title><script src="https://www.gstatic.com/firebasejs/7.21.1/firebase-app.js"></script><script src="https://www.gstatic.com/firebasejs/7.21.1/firebase-messaging.js"></script><script src="controller.js"></script></head><body>Firebase Cloud Messaging</body></html>

ให้ทำการ import Firebase script เข้ามา 2 ตัวด้วยกันคือ firebase-app.js กับ firebase-messaging.js จากนั้นให้ทำการสร้าง controller.js โดยใส่ code ดังนี้

// Configure Firebasevar firebaseConfig = {apiKey: "AIzaSyD4zhIMpv1ChBWRypY9e",authDomain: "peerless.firebaseapp.com",databaseURL: "https://peerless.firebaseio.com",projectId: "peerless",storageBucket: "peerless.appspot.com",messagingSenderId: "369073",appId: "1:369073:web:f2d1ae14448d"};firebase.initializeApp(firebaseConfig);// Using FCM Messagingconst messaging = firebase.messaging();messaging.usePublicVapidKey("BPhWo3Z0lYqisgfKxHKi53J822fQBSR3ZOU-TWLbNQV");// Get FCM Tokenmessaging.getToken().then((currentToken) => {if (currentToken) {console.log("Token: " + currentToken);} else {// Show permission request.console.log('No Instance ID token available. Request permission to generate one.');}}).catch((err) => {console.log('An error occurred while retrieving token. ', err);});

จาก Code ด้านบนที่สำคัญ ๆ คือต้อง Config firebase ซึ่ง config ต่าง ๆ จะมาให้เราตอนสร้าง Firebase project แล้ว หลังจาก Initial firebase เสร็จก็สร้าง Instance ของ messaging ขึ้นมาและ config VapidKey เข้าไป หลังจากนั้น getToken() ได้เลย

VapidKey (ใช้ Key pair ในส่วน Web Push certificates)

หลังจากลอง run website ก็จะขึ้น Error ดังรูปด้านล่าง

ปัญหาเกิดจาก “firebase-messaging-sw.js” เป็น file ที่ Firebase จะ call กลับมายังไฟล์นี้เนื่องจากใช้ในการทำ Background service ในการ Push notification ซึ่งจะเห็นได้ว่า Firebase เข้าผ่าน root directory ของ Server เลย ดังนั้นให้ไปสร้างไฟล์ “firebase-messaging-sw.js” โดยเป็นไฟล์เปล่า เพราะเราจะทดสอบ Background ก่อน

firebase-messaging-sw.js

หลัง Clear cache และทำการ Run ใหม่จะได้ FCM Token มาแล้ว

ทดสอบยิงผ่าน Postman โดยการ “ปิดหน้า Website”

URL

https://fcm.googleapis.com/fcm/send

Header

Authorization: key=AAAA34ACuPE:APA91bEFCOpB1aCcGU2P9PwFe21AyU-vAnbMa4f0msjqvtKIfXT0T-iGaRjh6CS
Content-Type: application/json

Body

{"to": "dsWP4-Ri91Z-qbkhHi_z3_:APA91bEHp0UN36zAV-OkEUK1hswVatQ8sf5uqY7YHDU-bUA4gmbhgtBxhkzvb8GvSF1epyOecTRfBKsTRPTOUUM7p4nX4YqljZUp_2RnX1gqXTp_ldRrJf6q9KkHWbv_9n7IKinqfw92","notification": {"title": "Title","body": "Description","click_action": "http://localhost:8888/WebPushNotification/"},"data":{"module": "Notification","data": {"title": "Test"}}}

ผลลัพธ์

แต่เมื่อเปิดเว็บขึ้นมาจะไม่มี Notification ขึ้นและไม่มีอะไรขึ้นมาเลยให้ทำการ Config “firebase-messaging-sw.js” เพิ่ม

importScripts('https://www.gstatic.com/firebasejs/7.21.1/firebase-app.js');importScripts('https://www.gstatic.com/firebasejs/7.21.1/firebase-messaging.js');firebase.initializeApp({apiKey: "AIzaSyD4zhIMpv1ChBW",authDomain: "peerless.firebaseapp.com",databaseURL: "https://peerless.firebaseio.com",projectId: "peerless",storageBucket: "peerless.appspot.com",messagingSenderId: "369073",appId: "1:369073:web:f2d1ae1444"});const messaging = firebase.messaging();

ส่วนไฟล์ controller.js เพิ่ม onMessage() เข้าไป

// Configure Firebasevar firebaseConfig = {apiKey: "AIzaSyD4zhIMpv1ChBW",authDomain: "peerless.firebaseapp.com",databaseURL: "https://peerless.firebaseio.com",projectId: "peerless",storageBucket: "peerless.appspot.com",messagingSenderId: "369073",appId: "1:369073:web:f2d1ae1444"};firebase.initializeApp(firebaseConfig);// Using FCM Messagingconst messaging = firebase.messaging();messaging.usePublicVapidKey("BPhWo3Z0lYqisgfKxHKi53J822fQBSR3ZOU");// Get FCM Tokenmessaging.getToken().then((currentToken) => {if (currentToken) {console.log("Token: " + currentToken);} else {// Show permission request.console.log('No Instance ID token available. Request permission to generate one.');}}).catch((err) => {console.log('An error occurred while retrieving token. ', err);});messaging.onMessage((payload) => {console.log('Message received. ', payload);});

จะได้ผลลัพธ์ดังนี้

ตอนนี้เราสามารถดัก Push notification on Foreground ได้แล้ว ให้ใช้คำสั่งในการ Create Notification เพิ่ม

messaging.onMessage((payload) => {console.log('Message received. ', payload);var notificationData = payload.notification;let title = notificationData.title;let body = notificationData.body;// Create notificationvar notification = new Notification(title, { body });notification.onclick = function(){window.parent.focus();notification.close();}});

ทดสอบยิง Postman ในขณะที่เปิด Website อยู่ จะได้ผลลัพธ์ดังด้านล่าง

--

--

No responses yet