如何在 React Native webview 中使用 PostMessage?

问题描述

我正在尝试将 postmessage 用于在 React Native 应用程序内的 web 视图中打开的页面。试了很多次,还是发不出去。

我可以正常收听网页消息。我就是无法寄回任何东西。

我目前正在使用 react-native-webview 11.6.5

export default function WebPage() {
  const webviewRef = useRef();

  const onMessage = (event) => {
    //receive message from the web page. working here until here
    const data = JSON.parse(event.nativeEvent.data);

    //reply the message
    webviewRef.current.postMessage(
      JSON.stringify({reply: 'reply'}),'*'
    )
  }

  return <View>
    <WebView
      ref={webviewRef}
      originWhitelist={['*']}
      source={{ uri: 'https://robertnyman.com/html5/postMessage/postMessage.html' }}
      domStorageEnabled
      javaScriptEnabled
      onMessage={onMessage}
    />
  </View>


}

知道我做错了什么吗?

更新:

感谢@Ahmed Gaber 的帮助,我找到了这个问题 https://github.com/react-native-webview/react-native-webview/issues/809 并发现他们正在将 postMessage 更改为 injectJavaScript

因此,我将代码 onMessage 更新为以下内容

const onMessage = (event) => {
  const data = JSON.parse(event.nativeEvent.data);

  //reply the message
  webviewRef.current.injectJavaScript(
    `window.postMessage(
      {
        reply: 'reply'
      }
    );`
  )
}

解决方法

将数据从应用发送到 const subjects = [ {name:"math"},{name:"sports"},{name:"math"},{name:"art"} ],subjectdates = [ {name:"math",year:2017},{name:"sports",year:2018},{name:"math",year:2019},{name:"art",year:2020} ]; const subjectDatesMap = subjectdates.reduce((map,item) => map.set( item.name,[...(map.get(item.name) || []),item] ),new Map); const addDates = subjects.map(classes => ({ subject: classes,end_subject_date: (subjectDatesMap.get(classes.name) || []).shift() })); console.log(addDates); 使用 injectedJavaScript
将数据从 webview 发送到应用使用 postMessage
webview 中接收由 webview 发送的数据数据,使用 onMessage

postMessage