Issues communicating an Ionic mobile app with InAppBrowser and a React web app using postMessage

60 Views Asked by At

I am working on two applications: one is a mobile app developed with Ionic and React using TypeScript, and the other is a web app developed with React. In the mobile app, I have integrated the "@ionic-native/in-app-browser" library to load a web page containing my previously developed React application.

My goal is to communicate these two applications to send data from the web app (React) to the mobile app (Ionic). For this purpose, I have been trying to use the JavaScript postMessage API, but I have not been successful in getting the communication to work properly.

In the mobile app, I have tried three different approaches to receive messages:

  1. I used window.addEventListener as follows:
window.addEventListener('message', function(e) {
    alert('message received');
});
  1. I also tried using browser.on('message') from "@ionic-native/in-app-browser":
browser.on('message').subscribe((event) => {
    alert('message received');
});
  1. I attempted to use browser.executeScript from "@ionic-native/in-app-browser":
const script = `
    window.addEventListener("message", async function(e) {
        const data = e.data;
        if (data.type === 'login_completed') {
            alert(data.type);
        }
    });
`;
browser.executeScript({ code: script });

In the web app (React), I sent the messages using window.parent.postMessage: window.parent.postMessage({ type: 'test' }, '*');

However, only the approach using window.parent.postMessage from the web app and browser.executeScript in the mobile app, seems to work, and it shows the alert. The other approaches do not receive any message.

I would like to know what could be the problem preventing communication in the other approaches and how I could solve it to receive the messages correctly in the mobile app.

Any help or advice would be greatly appreciated. Thank you!

0

There are 0 best solutions below