React Native Webview use

RN provides us with the WebView component to load a web page.

/**
 * Created by gyg on 2017/5/4.
 */
'use strict'
import React, {Component} from 'react';
import {
    StyleSheet,
    View,
    Text,
    WebView,
    BackAndroid,
} from 'react-native';

class WebLoadingView extends Component {

    render() {
        return (
            <View style={{flex:1,justifyContent:'center',
        alignItems:'center',backgroundColor:'#f2f2f2'}}>
                <Text style={styles.loadingText}>
                    The page is loading...
                </Text>
            </View>
        )
    }
}

export default class WebViewScene extends Component {

    // structure
    constructor(props) {
        super(props);
        // initial state
        this.state = {
            url: "",
            title: "",
            loading: true,
            isBackButtonEnable: false,
            isForwardButtonEnable: false
        };
    }

    componentDidMount() {
        BackAndroid.addEventListener("webHardwareBackPress", ()=> {
            try {
                if (this.state.isBackButtonEnable) {
                    this.refs._webView.goBack();//Return to the previous page
                    return true;//true system will no longer process false to the system
                }
            } catch (error) {
                return false;
            }
            return false;
        })
    }

    componentWillUnmount() {
        BackAndroid.removeEventListener("webHardwareBackPress");
    }

    render() {
        return (
            <View style={styles.container}>
                <WebView
                    style={styles.webView}
                    ref="_webView"
                    source={{uri:this.props.route.extras.url}}//Get URL parameters
                    automaticallyAdjustContentInsets={true}
                    domStorageEnabled={true}
                    javaScriptEnabled={true}
                    scalesPageToFit={true}
                    startInLoadingState={true}
                    renderLoading={()=>{return <WebLoadingView/>}}
                    onNavigationStateChange={this._onNavigationStateChange.bind(this)}
                />
            </View>
        )
    }

    //WebView navigation status changes
    _onNavigationStateChange(navState) {
        this.setState({
            url: navState.url,
            title: navState.title,
            loading: navState.loading,
            isBackButtonEnable: navState.canGoBack,
            isForwardButtonEnable: navState.canGoForward,
        })
    }
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: "#f2f2f2",
    },
    webview: {
        flex: 1,
    },
    loadingText: {
        color: '#8a8a8a',
        fontSize: 16
    }
})
  • source {uri: string, method: string, headers: object, body: string}, {html: string, baseUrl: string} Load url, load static html
  • javaScriptEnabled bool android is enabled to support js
  • automaticallyAdjustContentInsets bool Set whether to automatically adjust the content
  • domStorageEnabled bool Suitable for Android platform This is only suitable for Android platform, used to control whether to open DOM Storage (storage)
  • scalesPageToFit bool is suitable for iOS platform. It is used to set whether the web page is zoomed to adapt to the entire screen view and whether the user can change the zoom page
  • onError function is called when the webpage fails to load
  • onLoad function method is called when the web page is finished loading
  • onLoadEnd function is called when the page load ends (regardless of success or failure)
  • onLoadStart function is called when the web page loading starts
  • onNavigationStateChange function callback when the navigation state changes
  • renderError function is used when rendering view errors
  • renderLoading function The function of this function is to return a loading indicator
  • startInLoadingState bool force webview to display loading view when first loaded
  • userAgent string android set userAgent
  • allowsInlineMediaPlayback bool is suitable for the iOS platform. The setting determines when using HTML5 to play the video in the current page position or the native full-screen player. The default value is false. [Note]. In order to make the video play in the original web page position, not only must this attribute be set to true, but also the webkit-playsinline attribute of the video node in the HTML page must be set
  • bounces bool It is suitable for iOS platform. Set whether there is interface bounce feature
  • The onShouldStartLoadWithRequest function is suitable for the iOS platform. It should allow interception of the URL address loaded by WebView for custom processing. This method determines whether to continue loading the intercepted request by returning true or falase
  • scrollEnabled bool Suitable for iOS platform, used to set whether to enable page scrolling
    Jump to the display page:
this.props.navigator.push({
            component: WebViewScene,
            extras: {
                url: 'https://www.jd.com',//Web URL
            }
        })

Source code

Intelligent Recommendation

React native WebView encountered problems

Solution injectedJavascript should instead be the following (function(){   var originalPostMessage = window.postMessage;   var patchedPostMessage = function(message,targetOrigin,transfer){&n...

react-native-webview highly adaptive

Mobile terminal such as Android webview is based on the height of his own distraction, but RN has not, so how to do it? 2 one way easiest: usingreact-native-autoheight-webview How to use: Then use: Th...

React native webview communicates with H5

rn encapsulates native jsbridge to interact with H5 rn webview problem I wrote an article that encapsulates native webview before,rn encapsulates native jsbridge to interact with H5 But that’s o...

React Native development-component WebView

Preface When developing Android, we generally have some requirements to load web pages or execute some JavaScript. We all know that the control that implements this function in Android is WebView. The...

React Native learning eight-WebView

creates a native WebView that can be used to visit a web page. Screenshot Attributes iosallowsInlineMediaPlayback bool # Specify whether the HTML5 video is played at the current position of the w...

More Recommendation

React Native WebView optimization (iOS)

problem Opening a WebView in React Native will have a very obvious white screen time.   analyse problem I read some optimizations about WebView on the Internet, refer to the following WebView ope...

The interaction between React Native and WebView

1. Inject JavaScript into WebView When using injectJavaScript to inject javascript in webview, the method is as follows When injecting javascript strings through injectedJavaScript, only static text c...

React-Native WebView control usage

Like Android and IOS, there is also a control WebView that loads webpage data in React Native. Common methods are: source {uri: string, method: string, headers: object, body: string}, {html: string, b...

Introduction to React Native WebView plugin

In React Native, WebViews can allow mobile apps to access any web portal. In other words, the web view allows us to open a web URL in the app interface. Although React Native provides a built-in web v...

React-Native-WebView and H5 Communication

H5 sends data Window.reactnativeWebView.PostMessage ('event type type'); RN receives data (This.WebView is a react-native-webview instance by refs) Way, this.webview.injectjavascript ('H5 function nam...

Copyright  DMCA © 2018-2026 - All Rights Reserved - www.programmersought.com  User Notice

Top