Reputation: 509
I'm new in React Native.
I need to create communication between RN - Web - RN (RN to Web and then Web back to RN).
Assume i have list of item inside my web that called inside a webview. Each item inside list can be tapped/clicked. When i click one of item inside item list inside my web, i will redirect it to React Native apps page and show detail of realted item.
What i have done until now : I can inject Javascript from React Native to Webview like this :
<WebView
source={{uri: "myweb.com/webview.php"}}
injectedJavaScript={jsCode}
javaScriptEnabledAndroid={true}
style={{height: 100}} />
That code can open communication between React Native to Webpage inside webview, but i still fail to communication from Web inside webview to React Native. Can anyone explain, how to do it (and is it possible?)?
Upvotes: 7
Views: 16863
Reputation: 1127
import * as React from 'react';
import { Text, View, StyleSheet } from 'react-native';
import Constants from 'expo-constants';
import { WebView } from 'react-native-webview'
export default function App() {
const html = `
<html>
<head></head>
<body>
<script>
setTimeout(function(){
window.ReactNativeWebView.postMessage("hello")
},1000)
</script>
</body>
</html>
`;
return (
<>
<WebView
source = {{ html }}
onMessage={(event) => {
alert(event.nativeEvent.data);
}}
/>
</>
);
}
Upvotes: 0
Reputation: 2725
You need to use window.postMessage to communicate from Web to RN.
In your injectedJavascript do something like this:
const injectedJs = `
window.postMessage("Your message");
`;
(in your case, you will need to find the list DOM elements and use postMessage on every click)
And then on your WebView component read this message like so:
<WebView
source={{uri: "myweb.com/webview.php"}}
injectedJavaScript={injectedJs}
startInLoadingState
javaScriptEnabledAndroid={true}
javaScriptEnabled={true}
onMessage={event => {
alert('MESSAGE >>>>' + event.nativeEvent.data);
}}
/>
You can even send a json string as a message.
Upvotes: 10