react-native-webview / react-native-webview

React Native Cross-Platform WebView
https://github.com/react-native-community/discussions-and-proposals/pull/3
MIT License
6.31k stars 2.96k forks source link

Implementing MessageChannel in postMessage #3396

Closed andre-ols closed 1 week ago

andre-ols commented 2 months ago

Problem: The current implementation of postMessage in react-native-webview lacks the ability to create chained calls where the response is linked to a specific request. This makes it difficult to guarantee that a received response corresponds to the most recently sent message.

Solution proposal: I propose to implement the MessageChannel pattern in react-native-webview. This standard is already used in browsers to communicate with iframes and allows you to establish a secure bidirectional communication channel between React Native and the webview.

By implementing MessageChannel, we can achieve the following benefits:

Secure bidirectional communication: Messages can be sent and received in both directions, with the guarantee that the response is related to the specific request. Improved organization and control: Calls can be organized into specific channels, facilitating communication management and debugging. Familiar pattern for developers: The MessageChannel pattern is familiar to web developers, making it easier to integrate with existing web pages. We believe that implementing MessageChannel would be a valuable addition to react-native-webview and would improve the overall developer experience.

Example of use:

RN:

const sendMsgToWebview = () => {
  const channel = new MessageChannel();
  channel.port1.onmessage = (e) => {
    console.log("Response: ", e);
  };
  webviewRef.current?.postMessage("Message from RN", [channel.port2]);
};

Webview:

window.addEventListener("message", (e) => {
  console.log("Message from RN: ", e);
  e.ports[0].postMessage("Message from webview");
});
github-actions[bot] commented 2 weeks ago

Hello 👋, this issue has been opened for more than 2 months with no activity on it. If the issue is still here, please keep in mind that we need community support and help to fix it! Just comment something like still searching for solutions and if you found one, please open a pull request! You have 7 days until this gets closed automatically