Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
43
rated 0 times [  45] [ 2]  / answers: 1 / hits: 15554  / 7 Years ago, sun, december 3, 2017, 12:00:00

I'm trying to use the onMessage listener. The website is executing a postMessage (window.postMessage(Post message from web);) but react native's webview onMessage listener is not doing anything! I don't know what I'm doing wrong.



Here is the HTML



<script type=text/javascript>
window.postMessage(Post message from web);
</script>


And here is the react-native code:



  <WebView
ref={( webView ) => this.webView = webView}
onMessage={this.onMessage}
source={{uri: 'https://app.sodge.co/login/response.html'}}
/>


onMessage react native function:



onMessage( event ) {
Alert.alert(
'On Message',
event.nativeEvent.data,
[
{text: 'OK'},
],
{ cancelable: true }
)
}


Here is an expo snack too... I don't know that I'm doing wrong (: ...
https://snack.expo.io/S17AQqWbf


More From » html

 Answers
15

For anyone still confused about this... It is because communication between React Native and Webview has been completely rewritten. Yes, window.postMessage(data, *) has been changed to window.ReactNativeWebView.postMessage(data), but to answer this question specifically, the solution, i.e., what you need to support window.postMessage from your web view, is to pass the following prop per https://github.com/react-native-community/react-native-webview/releases/tag/v5.0.0:





const injectedJavascript = `(function() {
window.postMessage = function(data) {
window.ReactNativeWebView.postMessage(data);
};
})()`

<WebView
injectedJavaScript={injectedJavascript}
ref={( webView ) => this.webView = webView}
onMessage={this.onMessage}
source={{uri: 'https://app.sodge.co/login/response.html'}}
/>





Then you can call window.postMessage(Post message from web, *) within your script tag (or whereever else) as usual.



UPDATE: The above answer only supports the old functionality of window.postMessage on Android - something not mentioned in the docs. For iOS, simply use the library, https://github.com/CharlesStover/react-native-web-view. Include the web view as you would normally - without the injected javascript. iOS does not support messages or injected javascript between native and webview. For more information, and to understand the hack to get around this, check out https://medium.com/@Charles_Stover/fixing-react-native-webviews-postmessage-for-ios-10e2320b2f14.


[#55778] Wednesday, November 29, 2017, 7 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
korbindarrionh

Total Points: 598
Total Questions: 113
Total Answers: 104

Location: Burundi
Member since Wed, Nov 25, 2020
4 Years ago
;