Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

javascript - React Native WebView onMessage doesn't do anything

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...