如何使用聊天应用程序的 websocket 支持 Capacitor 中的推送通知

skB*_*ore -1 javascript push-notification ionic-framework capacitor

我没有找到任何正确的解决方案来使用 websocket 实现推送通知。

我的简单要求就像 WhatsApp 聊天一样,当消息到来时,它会以推送通知的形式显示该消息。

这是推送通知的文档。

/**
 *  Push notification code
*/


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);


/**
   Web Socket related code
*/

// Create WebSocket connection.
const socket = new WebSocket("ws://localhost:8080");

// Connection opened
socket.addEventListener("open", (event) => {
  socket.send("Hello Server!");
});

// Listen for 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
});

}
Run Code Online (Sandbox Code Playgroud)

小智 5

我建议不要使用 websocket 进行推送通知,因为 websocket 需要大量资源。当您的应用程序处于后台时,您也无法保持它,当您的应用程序不在前台时,手机的操作系统可能会限制您的应用程序的活动。我建议使用电容器插件,例如Capacitor Push notification。这些插件使用操作系统提供的底层方法。

此外,如果您正在使用基于 Web 的解决方案,那么开发 TLS Websocket 连接可能会具有挑战性。Webview 通常不提供对此类低级功能的直接访问。如果您最终想使用 Websocket,则需要实现本机解决方案。