Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implementing MessageChannel in postMessage #3396

Open
andre-ols opened this issue Apr 10, 2024 · 0 comments
Open

Implementing MessageChannel in postMessage #3396

andre-ols opened this issue Apr 10, 2024 · 0 comments
Labels
Type: feature request New feature or request

Comments

@andre-ols
Copy link

andre-ols commented Apr 10, 2024

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");
});
@andre-ols andre-ols added the Type: feature request New feature or request label Apr 10, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Type: feature request New feature or request
Projects
None yet
Development

No branches or pull requests

1 participant