Skip to content

Commit e5e296d

Browse files
authored
Update firebase-messaging-sw.js
1 parent 0ee0780 commit e5e296d

File tree

1 file changed

+32
-47
lines changed

1 file changed

+32
-47
lines changed

public/firebase-messaging-sw.js

Lines changed: 32 additions & 47 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,9 @@
11
// --- IMPORTANT: Service Worker for Background Messages ---
2-
// This file handles messages when your web app is not in the foreground.
3-
// It needs to import and initialize Firebase Messaging itself, using compat!
2+
// Handles Firebase background messages and notification click navigation
43

5-
// public/firebase-messaging-sw.js (using compat)
64
importScripts('https://www.gstatic.com/firebasejs/10.12.4/firebase-app-compat.js');
75
importScripts('https://www.gstatic.com/firebasejs/10.12.4/firebase-messaging-compat.js');
86

9-
// Your Firebase configuration @see src/firebase.config.ts
107
const firebaseConfig = {
118
apiKey: "AIzaSyDSTc5VVNNT32jRE4m8qr7hVbI8ahaIsRc",
129
authDomain: "peaceinthemiddleeast.firebaseapp.com",
@@ -20,68 +17,56 @@ const firebaseConfig = {
2017

2118
firebase.initializeApp(firebaseConfig);
2219

23-
let currentUserId = null;
24-
let processedMoveIds = new Set();
20+
console.log('Service Worker: Firebase initialized.');
2521

26-
console.log('Service Worker: Loaded and Firebase initialized.');
22+
const messaging = firebase.messaging();
2723

28-
firebase.messaging().onBackgroundMessage((payload) => {
29-
console.log('Received background message ', payload);
24+
messaging.onBackgroundMessage(payload => {
25+
console.log('Received background message', payload);
26+
27+
const { title, body } = payload.notification;
28+
const { player } = payload.data;
3029

31-
const notificationTitle = payload.notification.title;
3230
const notificationOptions = {
33-
body: payload.notification.body,
31+
body: body,
3432
icon: '/android-chrome-512x512.png',
35-
tag: payload.data.player || 'new_message', // Use player's UID as the tag
36-
icon: '/android-chrome-512x512.png'
33+
tag: player || 'new_message',
34+
data: {
35+
...payload.data,
36+
url: `${self.location.origin}/${player || ''}`
37+
}
3738
};
3839

39-
self.registration.showNotification(notificationTitle, notificationOptions);
40+
self.registration.showNotification(title, notificationOptions);
4041
});
4142

4243
self.addEventListener('notificationclick', event => {
43-
console.log('Service Worker: Notification clicked.', event.notification);
44+
console.log('Notification clicked:', event.notification);
4445
event.notification.close();
4546

46-
const friend = event.notification.data.player; // This is opponent's UID, used for URL path
47-
// const gameId = event.notification.data.gameId; // Game's unique key, if needed for other logic
48-
// const moveId = event.notification.data.moveId; // Move was removed when notification was shown
47+
const targetUrl = event.notification.data?.url || self.location.origin;
4948

50-
if (friend) {
51-
// App URL structure is /:friend (e.g., /user123)
52-
const targetUrl = `${self.location.origin}/${friend}`;
53-
event.waitUntil(
54-
clients.matchAll({ type: 'window', includeUncontrolled: true }).then(windowClients => {
55-
for (let i = 0; i < windowClients.length; i++) {
56-
const client = windowClients[i];
57-
// Check if a window/tab with this game (friend) is already open.
58-
if ((client.url === targetUrl || client.url === `${targetUrl}/`) && 'focus' in client) {
59-
console.log('Service Worker: Focusing existing window for friend:', friend);
60-
return client.focus();
61-
}
62-
}
63-
if (clients.openWindow) {
64-
console.log('Service Worker: Opening new window for friend:', friend);
65-
return clients.openWindow(targetUrl);
49+
event.waitUntil(
50+
clients.matchAll({ type: 'window', includeUncontrolled: true }).then(windowClients => {
51+
for (const client of windowClients) {
52+
if ((client.url === targetUrl || client.url === `${targetUrl}/`) && 'focus' in client) {
53+
console.log('Focusing existing window:', client.url);
54+
return client.focus();
6655
}
67-
})
68-
);
69-
} else {
70-
console.log('Service Worker: No friend in notification data, opening main page.');
71-
if (clients.openWindow) { // Fallback to open the main page
72-
return clients.openWindow('/');
73-
}
74-
}
56+
}
57+
if (clients.openWindow) {
58+
console.log('Opening new window to:', targetUrl);
59+
return clients.openWindow(targetUrl);
60+
}
61+
})
62+
);
7563
});
7664

7765
self.addEventListener('activate', event => {
78-
console.log('Service Worker: Activating...');
66+
console.log('Service Worker activating...');
7967
event.waitUntil(
80-
self.clients.claim().then(() => { // Take control of all clients immediately
68+
self.clients.claim().then(() => {
8169
console.log('Service Worker: Claimed clients.');
82-
// On activation, client should send 'SET_USER_ID' if user is logged in.
83-
// If SW persisted userId (e.g. in IndexedDB), it could be read here to setup listener early.
84-
// Example: restoreUserIdAndSetupListener();
8570
})
8671
);
8772
});

0 commit comments

Comments
 (0)