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

Comments

  1. Great blog.
    The details that you shared regarding React Native Application and the details that you shared in the form of coding. This simple blog with the application development code will help everyone to understand about React Native. I was searching for react native app development company and got his blog.
    Thanks for sharing such a great blog.

    ReplyDelete
  2. Thanks for sharing this wonderful information. I too learn something new from your post..
    React JS Training in Chennai

    ReplyDelete
  3. This comment has been removed by the author.

    ReplyDelete

Post a Comment

Popular posts from this blog

How to fix error : no module named sendgrid when try to use sendgrid python lib in PHP.

react-native run-android : sun.security.provider.cert path.SunCertPathBuilderException : unable to find valid certification path to req uested target

react-native run-android : do not build/update modified code(App.js)