The article directories

    • I. WebView component introduction
    • Two, WebView component use sample
      • 2.1 Loading Web Pages using URL Addresses
      • 2.2 Loading HTML Code
      • 2.3 RN and Html communication
      • 2.4 JavaScript Script Injection

I. WebView component introduction

The WebView component can load and display a web page through a URL, or pass in a piece of HTML code to display it. The main properties and methods are described below.

1. Main attributes

  • sourceIn:WebViewTo load a static segmenthtmlA code or aurl(You can also throw in someheaderOption);
  • automaticallyAdjustContentInsets: Sets whether to automatically adjust the content. Format:bool;
  • contentInset: Sets the size of the content. Format:{top: number, left: number, bottom: number, right: number};
  • injectJavaScriptInject a piece of JAVASCRIPT code before the page loads. The value is a string.
  • startInLoadingState: Indicates whether page loading is enabled. The value can be true or false.
  • bounces(iOS only) : Rebound feature. The default istrue. If set tofalse, the content is pulled to the bottom or the head does not bounce back.
  • scalesPageToFit(iOS only) : Used to set whether the page is scaled to adapt to the entire screen view, and whether the user can change the scaled page.
  • scrollEnabled(iOS only) : Set whether to enable page scrolling.
  • domStorageEnabled(Android only) : Controls whether to enable the functionDOM Storage(Storage).
  • javaScriptEnabled(Android only) : Enable or disableJavaScriptIn iOSWebViewIt’s on by default.

2. Main methods

  • onNavigationStateChange: called when the navigation state changes.
  • onLoadStart: called when the page starts to load.
  • onError: called when the web page fails to load.
  • onLoad: called when the page has finished loading.
  • onLoadEnd: called when the page finishes loading, whether it succeeds or fails.
  • renderLoading:WebViewThe function that is triggered when the component is rendering the page, onlystartInLoadingStateFor –trueWhen the function takes effect.
  • renderError: a function that listens for errors in rendering the page.
  • onShouldStartLoadWithRequest(iOS only) : This method allows interceptionWebViewURL address to be loaded for custom processing. The method passes the returntrueorfalseTo decide whether to continue loading the interception to the request.
  • onMessageIn:webViewInternal web page, callwindow.postMessageCan trigger this property corresponding to the function, throughevent.nativeEvent.dataGet the received data, implement the web page andRNData transfer between.
  • injectJavaScriptThe: function takes a string that is passed toWebViewAnd immediately execute asJavaScript.

Two, WebView component use sample

2.1 Loading Web Pages using URL Addresses

import React, {Component} from 'react';
import {
    AppRegistry,
    StyleSheet,
    Dimensions,
    Text,
    View,
    WebView
} from 'react-native';
 
// Get the width and height of the device
var {
    height: deviceHeight,
    width: deviceWidth
} = Dimensions.get('window');
 
// The container component of the default application
class App extends Component {
    / / rendering
    render() {
        return (
            <View style={styles.container}>
              <WebView bounces={false}
                scalesPageToFit={true}
                source={{uri:"https://shq5785.blog.csdn.net/",method: 'GET'}} style={{width:deviceWidth, height:deviceHeight}}> </WebView> </View> ); }}// Style definition
const styles = StyleSheet.create({
    container: {
        flex: 1,
        paddingTop:20}}); AppRegistry.registerComponent('HelloWorld', () => App);
Copy the code

2.2 Loading HTML Code

import React, {Component} from 'react';
import {
    AppRegistry,
    StyleSheet,
    Dimensions,
    Text,
    View,
    WebView
} from 'react-native';
 
// Get the width and height of the device
var {
    height: deviceHeight,
    width: deviceWidth
} = Dimensions.get('window');
 
// The container component of the default application
class App extends Component {
    / / rendering
    render() {
        return (
            <View style={styles.container}>
              <WebView bounces={false}
                scalesPageToFit={true}
                source={{html:"< h1 style =" color: # ff0000 "> welcome to visit https://shq5785.blog.csdn.net/ < / h1 >"}} style={{width:deviceWidth, height:deviceHeight}}> </WebView> </View> ); }}// Style definition
const styles = StyleSheet.create({
    container: {
        flex: 1,
        paddingTop:20}}); AppRegistry.registerComponent('HelloWorld', () => App);
Copy the code

2.3 RN and Html communication

Communication between HTML and RN can be achieved when the WebView loads the HTML. Rn sends data to HTML using the postMessage function. As follows:

RN:

 <WebView
    useWebKit={false}
    onLoad={() => {
      let data = {
        name: userInfo.usrName
      };
      this.webView.postMessage(JSON.stringify(data));
    }}
    onError={(event) => {
      console.log(`==webViewError:${JSON.stringify(event.nativeEvent)}`);
    }}
    onMessage={(event) => {
      this._onH5Message(event);
    }}
    automaticallyAdjustContentInsets={false}
    contentInset={{ top: 0, left: 0, bottom: - 1, right: 0 }}
    onScroll={(event) => this._onScroll(event)}
    style={styles.webview}
    source={this.html ? { html: this.html } : { uri: this.url }}
    bounces={false}
    showsHorizontalScrollIndicator={false}
    showsVerticalScrollIndicator={false} / >Copy the code

In the HTML:

// Register events in HTML to receive data from RN and display it in HTML
document.addEventListener('message', function listener(RnData) {
  messagesReceivedFromReactNative += 1;
  document.getElementsByTagName('p') [0].innerHTML =
    'React Native received messages:' + messagesReceivedFromReactNative;
  document.getElementsByTagName('p') [1].innerHTML = RnData.data;
  // Clear the listener immediately after receiving the data
  document.removeEventListener('message', listener)
});
Copy the code

Define a button in HTML and add an event to send data to RN:

//window.postMessage Sends data to rn
document.getElementsByTagName('button') [0].addEventListener('click', function() {
  window.postMessage('This is HTML sending a message to RN.');
});
Copy the code

After the window.postMessage function is called in HTML, the WebView onMessage function is called back to handle the data sent by HTML to RN. The sent data can be retrieved from e.ativeEvent. Data.

// Receive data sent by HTML
_onH5Message = (e) => {
  this.setState({
      messagesReceivedFromWebView: this.state.messagesReceivedFromWebView + 1,
      message: e.nativeEvent.data,
  })
  Alert.alert(e.nativeEvent.data)
}
Copy the code

2.4 JavaScript Script Injection

In Android development, this requires JavaScript support using the javaScriptEnabled attribute, which is supported by default on ios and does not exist. The function injectJavaScript (String) is provided in the WebView, which takes a String argument and can inject a script into the WebView as follows:

// Script injection
injectJS = () => {
  const script = 'document.write("Injected JS ")';  // eslint-disable-line quotes
  if (this.webview) {
     this.webview.injectJavaScript(script); }}Copy the code

  • WebView official document