【问题标题】:How to use PostMessage in a React Native webview?如何在 React Native webview 中使用 PostMessage?
【发布时间】:2021-09-20 20:12:11
【问题描述】:

我正在尝试将 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'
      }
    );`
  )
}

【问题讨论】:

    标签: reactjs react-native webview react-native-web react-native-webview


    【解决方案1】:

    要将数据从应用程序发送到webview,请使用injectedJavaScript
    将数据从webview 发送到应用程序使用postMessage
    要接收webview 中由postMessage 发送的数据数据,请使用onMessage

    //this Js function will be injected into the web page after the document finishes loading.
    //this function will Post a message to WebView.
    const INJECTED_JAVASCRIPT = `(function() {
        window.ReactNativeWebView.postMessage(JSON.stringify({key : "value"}));
    })();`;
    
    
    
    <WebView
      source={{ uri: 'https://reactnative.dev' }}
      injectedJavaScript={INJECTED_JAVASCRIPT}
      onMessage={(event) => {
           const data = JSON.parse(event.nativeEvent.data);
           alert(data.key);
      }}
    />;
    
    

    【讨论】:

    • 嗯...非常感谢您的帮助。感谢帮助,我发现他们正在将“postMessage”更改为“injectJavascript”,并且能够使用webviewRef.current.injectJavaScript(INJECTED_JAVASCRIPT) 解决它
    猜你喜欢
    • 2017-04-30
    • 2020-07-03
    • 2018-05-11
    • 2019-07-06
    • 2020-12-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多