react-native : communicate between react-native JS and WebView component

APIs:

window.postMessage in WebView, post a message to react-native JS.
onMessage callback in react-native JS, receive a message from WebView.
injectjavascript, Function that accepts a string that will be passed to the WebView and executed immediately as JavaScript.
injectedjavascript, Set this to provide JavaScript that will be injected into the web page when the view loads.

onMessage
A function that is invoked when the webview calls window.postMessage. Setting this property will inject a postMessage global into your webview, but will still call pre-existing values of postMessage.

window.postMessage accepts one argument, data, which will be available on the event object, event.nativeEvent.data.

data must be a string.

Sample code

import React, { Component } from 'react';
import {
  Button,
  Platform,
  StyleSheet,
  Text,
  View,
  WebView,
} from 'react-native';

var WEBVIEW_REF = 'webview';

export default class App extends Component<{}> {
  constructor(props) {
    super(props);
    this.onWebViewMessage = this.onWebViewMessage.bind(this);
    this.onShare = this.onShare.bind(this);
  }

  onWebViewMessage(event) {
    console.warn(event.nativeEvent.data);
    let msg;
    try {
      msg = JSON.parse(event.nativeEvent.data);
    } catch (err) {
      console.warn(err);
      return;
    }
    console.log(msg);
  }

  onShare() {
    var fetchAbstractJS = "(" + this.fetchAbstract.toString() + "());";
    console.log(fetchAbstractJS);
    this.refs[WEBVIEW_REF].injectJavaScript(fetchAbstractJS);
  }

  // function called in WebView via injectJavaScript
  fetchAbstract() {
    try {
      var title = document.querySelector('head title').innerText;
      var desc = document.querySelector('p').innerText;
      var imgurl = document.querySelector('p img').src;
      // post Message to react-native JS
      window.postMessage(JSON.stringify({'id' : 'ABSTRACT_FETCHED', 'url' : window.location.href, 'title' : title, 'desc' : desc, 'imgurl' : imgurl}), "*");
    } catch (err) {
      console.warn(err);
      return;
    }
  }

  render() {
    return (
    <View style={{flex:1}}>
      <WebView
        ref={WEBVIEW_REF}
        style={{flex:1}}
        onMessage={this.onWebViewMessage}
        source={{uri: 'https://manna.errong.win/let-s-growing-up-in-jesus/'}}
      />
      <Button
        onPress={this.onShare}
        title="Share"
        color="#841584"
        accessibilityLabel="Social Share"
      />
    </View>
    );
  }
}

react-native log-android

log-android

Refer

https://facebook.github.io/react-native/docs/webview.html#onmessage
https://facebook.github.io/react-native/docs/webview.html#injectjavascript
https://facebook.github.io/react-native/docs/webview.html#injectedjavascript

Subscribe to Post, Code and Quiet Time.

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
jamie@example.com
Subscribe