Skip to content
the poor coder

react native webview postmessage example

Poor Man
Published
Reading time
1 min read
On this page

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.

Keep going

2023

how to sort an array

How to Sort an Array If you have an array and you want to order its elements in a specific way, you need to use a sorting algorithm. There are several sorting algorithms available, but two of the most commonly used are…

javascript2 min read
2023

jquery mobile or desktop

jQuery Mobile or Desktop? As a web developer, I have had some experience with both jQuery Mobile and jQuery Desktop. Both frameworks have their pros and cons, and which one to use really depends on the specific project…

javascript1 min read
2023

node.js folder structure

Node.js Folder Structure If you are new to Node.js, it can be daunting to create a folder structure that will work for your project. The structure you choose will depend on the size and complexity of your project. Here…

javascript1 min read
ESC