BÀI 19: GỬI THÔNG BÁO ĐẨY VỚI FIREBASE CLOUD MESSAGING (FCM)

jk5587725

By jk5587725

Đăng ngày Tháng 7 7, 2025

Đây là một bước nâng cao rất thú vị và thực chiến: gửi thông báo đẩy (Push Notification) từ ứng dụng Vue PWA của bạn – cực kỳ hữu ích để:

  • Nhắc người dùng quay lại làm việc
  • Cập nhật todo mới
  • Gửi thông báo định kỳ như một app thật

Mục tiêu:

  • Cài đặt Firebase Cloud Messaging (FCM)
  • Đăng ký token người dùng
  • Gửi push notification đến client từ Firebase hoặc server
  • Tích hợp vào PWA đã build ở Bài 18

Phần 1: Tạo Firebase Project + Lấy FCM Config

  1. Truy cập: https://console.firebase.google.com
  2. Tạo Project mới: “Vue Todo App”
  3. Vào Project Settings > Cloud Messaging:
    • Lưu lại:
      • VAPID public key
      • Server key
  4. Tạo Web App:
    • Copy firebaseConfig (API key, projectId, messagingSenderId…)

Phần 2: Cài Firebase SDK

npm install firebase

Phần 3: Tạo file firebase-messaging-sw.js trong thư mục public/

importScripts('https://www.gstatic.com/firebasejs/10.5.2/firebase-app-compat.js');
importScripts('https://www.gstatic.com/firebasejs/10.5.2/firebase-messaging-compat.js');

firebase.initializeApp({
  apiKey: "API_KEY",
  authDomain: "xxx.firebaseapp.com",
  projectId: "xxx",
  messagingSenderId: "XXX",
  appId: "XXX"
});

const messaging = firebase.messaging();

messaging.onBackgroundMessage(payload => {
  self.registration.showNotification(payload.notification.title, {
    body: payload.notification.body,
    icon: '/pwa-192x192.png'
  });
});

Đây là Service Worker xử lý thông báo khi web đang đóng.

Phần 4: Khởi tạo Firebase Messaging trong main.js

import { initializeApp } from "firebase/app"
import { getMessaging, getToken, onMessage } from "firebase/messaging"

const firebaseConfig = {
  apiKey: "API_KEY",
  authDomain: "...",
  projectId: "...",
  messagingSenderId: "...",
  appId: "...",
  vapidKey: "VAPID_PUBLIC_KEY"
}

// Init Firebase
const appFirebase = initializeApp(firebaseConfig)
const messaging = getMessaging(appFirebase)

// Yêu cầu quyền gửi thông báo
Notification.requestPermission().then(permission => {
  if (permission === "granted") {
    getToken(messaging, { vapidKey: firebaseConfig.vapidKey })
      .then(currentToken => {
        if (currentToken) {
          console.log("🎯 Token:", currentToken)
          // Có thể gửi token về server để lưu
        }
      })
  }
})

// Khi đang mở web và nhận noti
onMessage(messaging, (payload) => {
  console.log("🔥 Foreground message:", payload)
  alert(payload.notification.title + " - " + payload.notification.body)
})

Phần 5: Gửi thử notification từ Firebase

  1. Vào Firebase Console → Cloud Messaging
  2. Chọn “Send Your First Message”
  3. Điền nội dung:
    • Tiêu đề: “Todo mới”
    • Nội dung: “Bạn còn 3 việc chưa hoàn thành”
  4. Chọn App Web (bạn đã tạo ở bước đầu)
  5. Gửi

Trình duyệt sẽ nhận noti ngay cả khi app đang đóng hoặc đang mở.

Bạn đã học được:

Kỹ năngVai trò
Firebase Cloud MessagingGửi thông báo real-time
firebase-messaging-sw.jsNhận noti khi app đang đóng
Notification.requestPermission()Hỏi quyền người dùng
getToken()Lấy token duy nhất của client
onMessage()Bắt sự kiện khi đang mở app

Bài tập mở rộng:

  1. Gửi noti định kỳ mỗi sáng: “Hôm nay bạn muốn hoàn thành việc gì?”
  2. Gửi noti mỗi khi thêm mới todo (qua backend)
  3. Làm hệ thống gửi noti từ chính dashboard admin bằng NodeJS + Express + FCM Server Key

📂 Chuyên mục:

Thảo luận

Email của bạn sẽ không được hiển thị công khai. Các trường bắt buộc được đánh dấu *

Đăng ký nhận tin mới

Nhận bài học, tài nguyên và cơ hội việc làm qua email hàng tuần.

[global_subscribe_form]

Chúng tôi cam kết không spam. Bạn có thể hủy bất cứ lúc nào.