Capacitor's push notification feature and websocket support for enhancing chat app functionality

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

}

Answer №1

I suggest steering clear of using websockets for push notifications due to their heavy resource consumption. Additionally, maintaining a websocket connection while your application is in the background can be problematic, as the phone's operating system may limit your app's capabilities when it's not in focus. Instead, I recommend utilizing capacitor plugins like Capacitor Push Notification, which leverage the OS's built-in functionalities.

Moreover, if you're dealing with web-based solutions, establishing a TLS websocket connection may pose challenges. Webviews typically lack direct access to such low-level features, necessitating the use of native solutions for websocket implementation in the long run.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Methods to fill a data table cell

I have recently created a table and I am facing an issue in populating the tds cells using JavaScript. The data for the table is coming from the server. Here's my table: <table id="report" class="infoRecurso" id='testExportId' style="wid ...

Unexpected behavior with Node js event listener

I am currently working on emitting and listening to specific events on different typescript classes. The first event is being listened to properly on the other class, but when I try to emit another event after a timeout of 10 seconds, it seems like the lis ...

What is the method for including a placeholder with sequential numbering?

When I click on the "Add String" button, it clones the first table row with an input in the table and adds it to the table. I also need to add a +1 number in the placeholder of the copied element. How can I determine the last placeholder before copying and ...

What is the best way to make a drop down menu list appear when I click on the parent li, and then show the sub li using JavaScript?

I have a code that includes an image, HTML, and CSS code. Can anyone please tell me how I can set up a drop-down menu list to open the sub <li> elements when I click on a parent <li> using JavaScript? You can see the appearance of the code in t ...

Prevent left click on HTML canvas and enable right click to pass through with pointer-events

In my scenario, I have an HTML canvas positioned above various other HTML elements that detect right-click mouse events. The goal is to be able to draw on the canvas with the left mouse button while simultaneously interacting with the underlying HTML eleme ...

The button remains stationary when it is clicked

After creating a button that should move to a random position upon being clicked, I encountered an issue with the document.style.top property not functioning as expected. I have already created two variables for height and width to generate random values, ...

Utilizing JavaScript to programmatically choose a row of radio buttons upon checkbox selection

Is there a way to determine if a checkbox is checked and then select all radio buttons within the same row? I have assigned id's to the elements for grouping purposes. This is what I am trying to accomplish: function select_row(row_id) { var chec ...

Combining JS Tree and Datatables for Enhanced Functionality

I am facing a challenge on my webpage where I have two columns. The left column consists of a checkbox jstree, while the right column contains a table using datatables. Both the table rows and tree are loaded at the start. My goal is to display a row when ...

Solution for resetting other elements to default when using a jQuery click function

I'm having an issue with a fixed sidebar that has an onclick function. Whenever I click on it at the bottom of the page, the content element scrolls back to the top of the page. How can I prevent this from happening? Below is the jQuery function I am ...

There seems to be an issue with Datatable not being able to apply filtering or

When using the JQuery Datatable plugin processing serverside, I am encountering an issue where the table is not getting refreshed when the dropdown selection is changed. The goal is to pass a value through the datatable to my PHP class which retrieves reco ...

Utilize Reactjs to efficiently showcase a collection of arrays within an object

I am struggling with a JSON file that has nested dropdown mega menu levels and I can't figure out how to map and render multiple levels of arrays and objects to create a tree-like structure. Here is my current JSON Structure: { "megamenu": [ { ...

Eliminate inner margin from the canvas of a bar chart created with ChartJS

I am looking to use Chart.js to create a single stacked bar chart that visualizes progress towards a specific financial goal. I have added a dotted line on top of the chart to represent this goal amount. The issue I am facing is that there is unwanted pad ...

Storing numerous sets of application credentials in Node.js using a specific design pattern

As I develop a node.JS server that communicates with Microsoft APIs, the server manages multiple applications created in Azure, each requiring a configured Client ID and Client secret. I have implemented a strategy to switch between these credentials based ...

TextGeometry failing to render

Currently experimenting with TextGeometry. Successfully implemented BoxGeometry, but encountering issues with TextGeometry. Experimenting with different material options like MeshNormalMeterial, however, still unable to resolve the issue var scene = new ...

Difficulties accessing MongoDb database using Node.js

Having issues when trying to read this data collection using mongoose and Node.js: I have a single JSON object within my Collection and I'm attempting to access it with the following code: materias.find().exec(function(err1,materias){ if(err ...

Determining the width of a window using JavaScript

My website is experiencing some mysterious issues with $(window).width(). When I open my site in the Chrome Device Toolbar with a window size of 320xXXX, then run $(window).width() in Google Chrome's JavaScript console, it returns 980. As a result, n ...

Is there a more effective method to return a response apart from using a redundant function?

function unnecessaryFunction(){ let details: SignInDetails = { user: user, account: account, company: company }; return details; } I am being told that the details value is unnecessary. Is there ...

Tips for preventing Django template from showing up prior to VueJS rendering

I am currently facing an issue with rendering a Django template using VueJs through CDN. Upon loading the page, I notice that the raw Django code is displayed initially before being rendered by VueJs, which typically takes less than a second. To fetch dat ...

Tips on creating a required field for file type in AngularJS

Greetings! Currently, I am in the process of developing a web application using AngularJS. One of the modules I am working on involves file uploads, which are being handled dynamically. The list of files to be uploaded is retrieved through an API call, and ...

Optimizing JSON data by recursively removing empty values, converting strings to booleans, and trimming whitespace using jq - best practices?

During data preprocessing, I have the task of eliminating all empty values from an input JSON. This includes removing empty arrays [], empty objects {}, and various forms of empty strings like "", " ", and "\t". Additio ...