Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

window.ReactNativeWebView.postMessage not working in React JS for passing data from WebViews to React Native

I have a Web Application in React JS which is hosted in Netlify. The same is embedded in React Native using WebViews. I want to pass data from React JS to React Native.

I tried window.ReactNativeWebView.postMessage("hello") in React JS, but the onMessage is not being invoked in React Native Webview.

React JS Code -

await window.ReactNativeWebView.postMessage("Hello!");

React Native Code -

 return (
    <View style={styles.container}>
      <WebView
        source={{ uri: 'hosted netlify link' }}
        ref={webViewRef}

        onMessage={(event) =>
          { 
          console.log("INSIDE ON MESSAGE"); 
          alert(event.nativeEvent.data); }
          }

        style={styles.view}
        originWhitelist={['*']}
        allowsInlineMediaPlayback
        javaScriptEnabled={true}
        scalesPageToFit
        mediaPlaybackRequiresUserAction={false}
        javaScriptEnabledAndroid
        useWebkit
        startInLoadingState={true}
        renderLoading={Spinner}
        geolocationEnabled={true}
      />
    </View>
  );

Please help me in passing data from React JS to React Native.

Thank you in advance.

like image 345
sureshtechi Avatar asked Sep 12 '25 15:09

sureshtechi


1 Answers

I struggled with this for a while, here is a working solution that solved my issue.

On your React JS side add the following to post the message to React Native:

  window["ReactNativeWebView"] && window["ReactNativeWebView"].postMessage(JSON.stringify({"key": "value"})). 

Please note that you must pass only one string argument.

like image 139
Mark Kazakov Avatar answered Sep 14 '25 05:09

Mark Kazakov