react native webview postmessage example

React Native Webview Postmessage Example

If you are looking to communicate between a React Native app and a webview, you can use the postMessage API.

Step 1: Create a webview component

You can create a webview component in React Native using the WebView component from the 'react-native-webview' library.

import React from 'react'; import { WebView } from 'react-native-webview'; const MyWebView = () => { return ( <WebView source={{ uri: '' }} /> ); }; export default MyWebView;

Step 2: Listen for postMessage in webview

In your webpage, you can add an event listener for the 'message' event and parse the data from the postMessage event.

window.addEventListener("message", (event) => { const message = event.data; console.log(message); });

Step 3: Send postMessage from React Native app

In your React Native app, you can use the webview's injectJavaScript method to execute JavaScript code in the webview.

const MyWebView = () => { const webViewRef = useRef(); const onMessage = (event) => { console.log(event.nativeEvent.data); }; useEffect(() => { const postData = { message: 'Hello from React Native!' }; const postDataString = JSON.stringify(postData); webViewRef.current.injectJavaScript(`window.postMessage(${postDataString}, "*")`); }, []); return ( <WebView ref={webViewRef} source={{ uri: '' }} onMessage={onMessage} /> ); };

This example sends a postMessage with the data {'{'}message: 'Hello from React Native!'{'}'} to the webview when it first loads. The onMessage function logs the data received from the postMessage event.

That's it! With these steps, you can communicate between your React Native app and a webview using postMessage.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe