Capture WebView Communication

#1

I’m working on an app where I need to interact with a webview. Essentially I need to call a function in the webview and capture (somehow) what it returns.

Essentially the parent class has a button. This buttons triggers a function called in the child class which sends a message to the webview. The webview then sends a message back which triggers the onMessage() function. So my question basically is, How can the parent function testFunc() access the data the webview returned.

Here is a simplified example of the child class.

export default class Child extends Component {
  sendMessageToWebView = () => {
    this.webview.postMessage("Hello WebView, from React Native");
  }

  html = () => {
    `<body>
     <script>
       document.addEventListener("message", function(data) {
         console.log(data);
         window.postMessage("Hello from WebView :)");
       });
     </script>
    </body>`
  }

  onMessage = (data) => {
    console.log(data.nativeEvent.data);
    return data.nativeEvent.data;
  }


  render() {
    return (
      <View>
        <WebView
          ref={(view) => { this.webview = view; }}
          source={{ html() }}
          onMessage={this.onMessage}
        />
      </View>
    );
  }
}

Here is an example of the parent class

export default class Parent extends Component {
  testFunc = () => {
    this.child.sendMessageToWebView();
  }

  render() {
    return (
      <View>
         <Button onPress={this.testFunc} title={'Test'} />
         <Child ref={child => {this.child = child}} />
      </View>
    );
  }
}

I have thought about using states, but I end up with a similar problem. How does the parent function know when the state has been changed in the child class.

Snack Link: https://snack.expo.io/@hmajid2301/webview-communication-test

Any help would be greatly appreciated thanks.

closed #2

This topic was automatically closed 15 days after the last reply. New replies are no longer allowed.