乐闻世界logo
搜索文章和话题

How to use PostMessage in a React Native webview?

1个答案

1

1. Setting up the WebView Component in React Native

First, set up a WebView component in your React Native code and assign a ref to it for sending messages later:

jsx
import React, { useRef } from 'react'; import { WebView } from 'react-native-webview'; const MyComponent = () => { const webviewRef = useRef(null); return ( <WebView ref={webviewRef} source={{ uri: 'https://your-website.com' }} onMessage={event => { // Handle messages received from the web page console.log('Received message from web:', event.nativeEvent.data); }} /> ); };

2. Sending Messages to the Web Page

When you need to send messages to the embedded web page, use the postMessage method. For example, you can send a message when a user clicks a button:

jsx
const sendMessageToWeb = () => { const message = 'Hello from React Native!'; webviewRef.current.postMessage(message); }; // Call this function in your UI, for example, as the onPress event handler of a button

3. Receiving and Sending Messages in the Web Page

In your web page JavaScript code, add code to listen for message events. Additionally, you can send messages back to the React Native application using window.postMessage.

html
<!DOCTYPE html> <html lang="en"> <head> <!-- Omitted other head information --> <script> // Listen for messages from the React Native application window.addEventListener('message', event => { console.log('Received message from React Native:', event.data); // Perform appropriate actions, such as modifying the DOM based on the message // Send a message to the React Native application window.ReactNativeWebView.postMessage('Hello from web!'); }); </script> </head> <body> <!-- Web page content --> </body> </html>

Note: When sending messages in the web page code, use the window.ReactNativeWebView.postMessage method, which is the standard way to communicate with the React Native WebView component.

4. Handling Messages from the Web Page

In the React Native code, you have already set up the onMessage property to handle messages received from the web page. Whenever the web page sends a message via postMessage, the onMessage event is triggered, and you can receive and process these messages within the event handler.

The above steps demonstrate how to use the postMessage method through the WebView component in React Native to achieve bidirectional communication with embedded web pages. This technique can be used in various scenarios, such as notifying the React Native application after a web form submission or passing scores and states in embedded games.

2024年6月29日 12:07 回复

你的答案