В фоновом/выключенном состоянии: уведомления приходят, отображаются, и нажатие на них запускает правильное событие (pushNotificationActionPerformed) для глубокой связи с приложением.
В состоянии переднего плана:
Событие pushNotificationReceived срабатывает, как и ожидалось.
Однако нажатие уведомление не запускает pushNotificationActionPerformed, поскольку уведомление не отображается изначально.
Я реализовал временное решение для отображения уведомлений через Toast-сообщения на переднем плане, но это не идеально, поскольку оно не копирует встроенное поведение уведомлений.
Конфигурация конденсатора (capacitor.config.ts)
presentationOptions: ["badge", "sound", "alert"]
}
Код внешнего интерфейса (NotificationService)
console.log('
const { title, body } = notification;
const data = notification.data || {};
await this.presentToastNotification(
title || 'New Notification',
body || 'You have a new message',
data?.conversacionId
);
console.log('
});
Уведомление о маршруте Backend nodejs
notificacionRuta.post('/crear-notificacion', async (req: Request, res: Response) => {
try {
const { receptorId, mensaje, titulo, conversacionId } = req.body;
if (!titulo || !mensaje || !receptorId || !conversacionId) {
return res.status(400).json({ error: 'El título, mensaje, receptorId y conversacionId son obligatorios.' });
}
// Crear y guardar la notificación
const notificacion = new Notificacion({
usuarioDestino: receptorId,
mensaje,
titulo,
fecha: new Date(),
tipo: 'mensaje',
leido: false,
});
const savedNotificacion = await notificacion.save();
console.log('
// Obtener los tokens del usuario
const receptor = await Usuario.findById(receptorId);
if (!receptor || !receptor.deviceTokens || receptor.deviceTokens.length === 0) {
return res.status(404).json({ error: 'Token del dispositivo no encontrado' });
}
// Enviar notificación push
await sendPushNotificationMultiple(receptor.deviceTokens, mensaje, titulo, receptorId, conversacionId);
res.status(201).json(savedNotificacion);
} catch (error) {
console.error('
logger.error('Error al crear notificación', { error: JSON.stringify(error, null, 2) });
res.status(500).json({ error: 'Error al crear notificación', details: error });
}
});
/**
* Función para enviar notificación push a múltiples dispositivos
*/
async function sendPushNotificationMultiple(
tokens: string[],
mensaje: string,
titulo: string,
receptorId: string,
conversacionId: string
) {
try {
if (!tokens || tokens.length === 0) {
throw new Error('No hay tokens de dispositivos válidos para enviar la notificación.');
}
const payload = {
notification: {
title: titulo,
body: mensaje,
},
data: {
title: titulo,
body: mensaje,
type: 'chat',
conversacionId: conversacionId,
receptorId: receptorId,
},
android: {
priority: 'high' as const,
notification: {
channelId: 'default',
},
},
apns: {
payload: {
aps: {
contentAvailable: true,
alert: {
title: titulo,
body: mensaje,
},
},
},
headers: {
'apns-priority': '10',
},
},
};
const response = await admin.messaging().sendEachForMulticast({
tokens,
notification: payload.notification,
data: payload.data,
android: payload.android,
apns: payload.apns,
});
console.log('
const invalidTokens: string[] = [];
response.responses.forEach((resp, idx) => {
if (!resp.success) {
console.error(
`
);
if (resp.error?.code === 'messaging/registration-token-not-registered') {
invalidTokens.push(tokens[idx]);
}
}
});
if (invalidTokens.length > 0) {
await Usuario.updateOne(
{ _id: receptorId },
{ $pull: { deviceTokens: { $in: invalidTokens } } }
);
console.log('
}
} catch (error) {
console.error('
throw error;
}
}
Подробнее здесь: https://stackoverflow.com/questions/793 ... foreground
Мобильная версия