Skip to content

feat: Integrate Firebase Cloud Messaging (FCM) #3

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions index.html
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,14 @@

<h1>VinF - Hybrid Inference - Bug Bash</h1>

<div id="fcmSection">
<h3>FCM Status</h3>
<p id="fcmToken">FCM Token: Waiting...</p>
<h4>Foreground Notifications:</h4>
<div id="foregroundNotificationDisplay" style="border: 1px solid #ccc; padding: 10px; min-height: 50px;">
<!-- Foreground messages will appear here -->
</div>
</div>
<br/><br/>

<h2>Text Only Input</h2>
Expand Down
55 changes: 55 additions & 0 deletions public/firebase-messaging-sw.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
// Import the Firebase app and messaging modules
import { initializeApp } from 'firebase/app';
import { getMessaging, onBackgroundMessage } from 'firebase/messaging/sw'; // Note: using firebase/messaging/sw

// Your web app's Firebase configuration (taken from src/app.ts)
// IMPORTANT: Make sure this config is identical to the one in src/app.ts
const firebaseConfig = {
apiKey: "*", // Replace with your actual apiKey if not using a placeholder
authDomain: "vertexaiinfirebase-test.firebaseapp.com",
projectId: "vertexaiinfirebase-test",
storageBucket: "vertexaiinfirebase-test.firebasestorage.app",
messagingSenderId: "857620473716",
appId: "1:857620473716:web:8c803ada68ede9b2bb6e21"
};

// Initialize Firebase
const app = initializeApp(firebaseConfig);
const messaging = getMessaging(app);

onBackgroundMessage(messaging, (payload) => {
console.log('[firebase-messaging-sw.js] Received background message ', payload);

// Customize notification here
const notificationTitle = payload.notification?.title || 'Background Message';
const notificationOptions = {
body: payload.notification?.body || 'Something happened in the background',
icon: payload.notification?.icon || '/images/dog.jpg' // Default icon
};

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

// Optional: Add event listeners for notification click
self.addEventListener('notificationclick', function(event) {
console.log('[firebase-messaging-sw.js] Notification click Received.', event.notification);
event.notification.close();

// Example: Focus or open a window
// event.waitUntil(
// clients.matchAll({ type: 'window', includeUncontrolled: true }).then(function(clientList) {
// if (clientList.length > 0) {
// let client = clientList[0];
// for (let i = 0; i < clientList.length; i++) {
// if (clientList[i].focused) {
// client = clientList[i];
// }
// }
// return client.focus();
// }
// return clients.openWindow('/'); // Open your app's root page
// })
// );
});

console.log('[firebase-messaging-sw.js] Service worker registered and listening for background messages.');
48 changes: 48 additions & 0 deletions src/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import {


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


const firebaseConfig = {
Expand All @@ -21,6 +22,7 @@ const firebaseConfig = {

// Initialize Firebase
const app = initializeApp(firebaseConfig);
const messaging = getMessaging(app);

// Initialize the Vertex AI service
// const vertexAI = getVertexAI(app);
Expand Down Expand Up @@ -203,7 +205,53 @@ async function fileToGenerativePart(file: Blob) {


// --- Event Listener Setup ---

async function requestNotificationPermissionAndToken() {
console.log("Requesting notification permission...");
try {
const permission = await Notification.requestPermission();
if (permission === "granted") {
console.log("Notification permission granted.");
// TODO: Replace 'YOUR_VAPID_KEY' with your actual VAPID key from the Firebase console.
// You will need to generate this key in the Firebase console under Project settings > Cloud Messaging > Web configuration.
const currentToken = await getToken(messaging, { vapidKey: "YOUR_VAPID_KEY_REPLACE_ME" });
if (currentToken) {
console.log("FCM Token:", currentToken);
// You would typically send this token to your server to store it.
// For display in this example, let's add it to a DOM element if it exists.
const tokenElement = document.getElementById('fcmToken');
if (tokenElement) {
tokenElement.textContent = `FCM Token: ${currentToken}`;
}
} else {
console.log("No registration token available. Request permission to generate one.");
}
} else {
console.log("Unable to get permission to notify.");
}
} catch (error) {
console.error("An error occurred while requesting permission or getting token: ", error);
}
}

onMessage(messaging, (payload) => {
console.log("Message received in foreground: ", payload);
// Customize notification handling here.
// For example, show an alert or update the UI.
alert(`Foreground message received: ${payload.notification?.title || 'New Message'}`);

// You could also display this information in a dedicated part of your UI.
const notificationDisplay = document.getElementById('foregroundNotificationDisplay');
if (notificationDisplay) {
notificationDisplay.innerHTML +=
`<p><strong>${payload.notification?.title || 'Notification'}</strong>: ${payload.notification?.body || ''}</p>`;
}
});

document.addEventListener('DOMContentLoaded', () => {
// Request notification permission and get token right away
requestNotificationPermissionAndToken();

const bTextOnlyInference = document.getElementById('bTextOnlyInference') as HTMLButtonElement;
const bTextAndImageInference = document.getElementById('bTextAndImageInference') as HTMLButtonElement;

Expand Down