Firebase API не отправляет уведомления в фоновом режиме
Я создаю веб-приложение с помощью Django и пытаюсь отправлять push-уведомления через firebase API. Это работает, когда пользователь находится на странице, которая регистрирует firebase-messaging-sw.js, но в фоновом режиме уведомления не приходят, хотя ошибок не возникало.
def send_fcm_notification(device_token, title, body, data=None, click_action=None):
headers = {
"Authorization": f"Bearer {get_access_token()}",
"Content-Type": "application/json",
}
data = {
"message": {
"token": device_token, # Use "topic": "your-topic" to send to a topic
"notification": {
"title": title,
"body": body,
},
"data": data or {},
"android": {
"priority": "high"
},
"apns": {
"payload": {
"aps": {
"alert": {
"title": title,
"body": body
}
}
}
}
}
}
response = requests.post(FCM_ENDPOINT, headers=headers, data=json.dumps(data))
return response.json()
SW
importScripts("https://www.gstatic.com/firebasejs/11.2.0/firebase-app-compat.js");
importScripts("https://www.gstatic.com/firebasejs/11.2.0/firebase-messaging-compat.js");
// Firebase Configuration (Same as in your main script)
const firebaseConfig = {
//myconfig data
};
// Initialize Firebase
firebase.initializeApp(firebaseConfig);
const messaging = firebase.messaging();
self.addEventListener('notificationclick', (event) => {
event.notification.close(); // CLosing the notification when clicked
const urlToOpen = event?.notification?.data?.url || 'https://www.test.com/';
// Open the URL in the default browser.
event.waitUntil(
clients.matchAll({
type: 'window',
})
.then((windowClients) => {
// Check if there is already a window/tab open with the target URL
for (const client of windowClients) {
if (client.url === urlToOpen && 'focus' in client) {
return client.focus();
}
}
// If not, open a new window/tab with the target URL
if (clients.openWindow) {
return clients.openWindow(urlToOpen);
}
})
);
});
// Handle background notifications
messaging.onBackgroundMessage((payload) => {
console.log("Received background message:", payload);
self.registration.showNotification(payload.notification.title, {
body: payload.notification.body,
icon: payload.notification.image || "/static/img/favicon.ico",
data: { url: payload?.data?.url || 'https://www.test.com/'},
});
});
index.html
Я думаю, что единственная причина, по которой он работает, пока страница открыта - это функция onMessage в index.html