javascriptreact-nativewebview

How to communcation between web inside webview back to react native apps


I'm new in React Native.

I need to create communication between RN - Web - RN (RN to Web and then Web back to RN).

Assume i have list of item inside my web that called inside a webview. Each item inside list can be tapped/clicked. When i click one of item inside item list inside my web, i will redirect it to React Native apps page and show detail of realted item.

What i have done until now : I can inject Javascript from React Native to Webview like this :

<WebView
  source={{uri: "myweb.com/webview.php"}}
  injectedJavaScript={jsCode}
  javaScriptEnabledAndroid={true}
  style={{height: 100}} />

That code can open communication between React Native to Webpage inside webview, but i still fail to communication from Web inside webview to React Native. Can anyone explain, how to do it (and is it possible?)?


Solution

  • You need to use window.postMessage to communicate from Web to RN.

    In your injectedJavascript do something like this:

    const injectedJs = `
      window.postMessage("Your message");
    `;
    

    (in your case, you will need to find the list DOM elements and use postMessage on every click)

    And then on your WebView component read this message like so:

    <WebView
        source={{uri: "myweb.com/webview.php"}}
        injectedJavaScript={injectedJs}
        startInLoadingState
        javaScriptEnabledAndroid={true}
        javaScriptEnabled={true}
        onMessage={event => {
          alert('MESSAGE >>>>' + event.nativeEvent.data);
        }}
    />
    

    You can even send a json string as a message.