Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
1.1k views
Welcome To Ask or Share your Answers For Others

1 Answer

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'}}
/>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...