Home > Web Front-end > JS Tutorial > Detailed explanation of communication examples between react native and webview

Detailed explanation of communication examples between react native and webview

巴扎黑
Release: 2017-09-26 09:36:13
Original
3269 people have browsed it

This article mainly introduces the sample code for communication between react native and webview. The editor thinks it is quite good, so I will share it with you now and give it as a reference. Let’s follow the editor and take a look.

WebView is a component in ReactNative. It can create a native WebView that can be used to access a web page.

Sometimes we need to RN communicates with WebView, or transmits data, or sends message notifications. At this time, the following knowledge must be used.

1: WebView to RN Send data from the end:

First, we build a webview:


##

<WebView
  ref={&#39;webview&#39;}
  source={require(&#39;./index.html&#39;)}
  style={{width: 375, height: 220}}
  onMessage={(e) => {
    this.handleMessage(e)
  }}
  
/>
Copy after login

You can see that there is an onMessage method ,


onMessage function

The function corresponding to this attribute can be triggered when the window.postMessage method is called in the webpage inside the webview, thereby realizing data exchange between the webpage and RN. When setting this property, a postMessage global function will be injected into the webview and override the implementation of the same name that may already exist.

Window.postMessage on the web page only sends one parameter data, which is encapsulated in the event object on the RN side, namely event.nativeEvent.data. data can only be a string.

It can be seen that this method is used to receive data from Webview (that is, html).


The internal implementation is to process the received data:



handleMessage(e) {
  this.setState({webViewData: e.nativeEvent.data});
}
Copy after login

e.nativeEvent.data is the data sent from inside the webview.


Just doing this is not enough, this is just For Rn side processing, we also need to write a method of sending data in html:



var data = 0;

function sendData(data) {
  if (window.originalPostMessage) {
    window.postMessage(data);
  } else {
    throw Error(&#39;postMessage接口还未注入&#39;);
  }
}
document.getElementById(&#39;button&#39;).onclick = function () {
  data += 100;
  sendData(data);
}
Copy after login

window.postMessage is to send data to RN.

Two: RN sends data to Webview:

First define a method to send data:



sendMessage() {
  this.refs.webview.postMessage(++this.data);
}
Copy after login

This step is very simple.

Just write the data you want to send as a parameter in this method.

Then, there must also be a corresponding method for receiving data in the html:



window.onload = function () {
  document.addEventListener(&#39;message&#39;, function (e) {
    document.getElementById(&#39;data&#39;).textContent = e.data;
  });

}
Copy after login

This enables communication between Rn and Webview.


Put the source code afterwards:



<!DOCTYPE html>
<html lang="en">
<head>
  <title></title>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<p style="text-align: center">
  <button id="button">发送数据到react native</button>
  <p style="text-align: center">收到react native发送的数据: <span id="data"></span></p>
</p>
<script>
  var data = 0;

  function sendData(data) {
    if (window.originalPostMessage) {
      window.postMessage(data);
    } else {
      throw Error(&#39;postMessage接口还未注入&#39;);
    }
  }

  window.onload = function () {
    document.addEventListener(&#39;message&#39;, function (e) {
      document.getElementById(&#39;data&#39;).textContent = e.data;
    });
    document.getElementById(&#39;button&#39;).onclick = function () {
      data += 100;
      sendData(data);
    }
  }
</script>
</body>
</html>
Copy after login

web.js:



/**
 * Created by 卓原 on 2017/8/17.
 * zhuoyuan93@gmail.com
 */
import React from &#39;react&#39;;
import {
  View,
  Text,
  StyleSheet,
  WebView
} from &#39;react-native&#39;;

export default class Web extends React.Component {

  constructor(props) {
    super(props);
    this.state = {
      webViewData: &#39;&#39;
    }
    this.data = 0;
  }

  sendMessage() {
    this.refs.webview.postMessage(++this.data);
  }

  handleMessage(e) {
    this.setState({webViewData: e.nativeEvent.data});
  }

  render() {
    return (
      <View style={styles.container}>
        <View style={{width: 375, height: 220}}>
          <WebView
            ref={&#39;webview&#39;}
            source={require(&#39;./index.html&#39;)}
            style={{width: 375, height: 220}}
            onMessage={(e) => {
              this.handleMessage(e)
            }}

          />

        </View>
        <Text>来自webview的数据 : {this.state.webViewData}</Text>
        <Text onPress={() => {
          this.sendMessage()
        }}>发送数据到WebView</Text>
      </View>
    )
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    marginTop: 22,
    backgroundColor: &#39;#F5FCFF&#39;,
  },

});
Copy after login

The above is the detailed content of Detailed explanation of communication examples between react native and webview. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template