I'm struggling to integrate push notifications with WebSockets effectively.
My goal is to display incoming messages as push notifications, similar to how WhatsApp handles chat messages.
For detailed guidance on implementing push notifications, check out the documentation.
/**
* Code for Push Notifications
*/
import { PushNotifications } from '@capacitor/push-notifications';
const addListeners = async () => {
await PushNotifications.addListener('registration', token => {
console.info('Registration token: ', token.value);
});
await PushNotifications.addListener('registrationError', err => {
console.error('Registration error: ', err.error);
});
await PushNotifications.addListener('pushNotificationReceived', notification => {
console.log('Push notification received: ', notification);
});
await PushNotifications.addListener('pushNotificationActionPerformed', notification => {
console.log('Push notification action performed', notification.actionId, notification.inputValue);
});
}
const registerNotifications = async () => {
let permStatus = await PushNotifications.checkPermissions();
if (permStatus.receive === 'prompt') {
permStatus = await PushNotifications.requestPermissions();
}
if (permStatus.receive !== 'granted') {
throw new Error('User denied permissions!');
}
await PushNotifications.register();
}
const getDeliveredNotifications = async () => {
const notificationList = await PushNotifications.getDeliveredNotifications();
console.log('delivered notifications', notificationList);
/**
WebSocket Implementation
*/
// Establish WebSocket connection.
const socket = new WebSocket("ws://localhost:8080");
// Connection established
socket.addEventListener("open", (event) => {
socket.send("Hello Server!");
});
// Listen for incoming messages
socket.addEventListener("message", (event) => {
console.log("Message from server ", event.data);
PushNotifications.send("Message from server ", event.data); // added for testing but does not work
});
}