6

When the webview loads an invalid url, which property should I set to display an error view? I try renderError, it triggers the console message but did not display the view.

here's the code:

<View style={styles.webview_body}>
  <WebView
   source={{uri:this.props.url}}
   onNavigationStateChange={this.onNavigationStateChange.bind(this)}
   renderError={this.loadError.bind(this)}
 />
</View>

//the fucntion which display the error message
loadError(){
console.log('loaded');
return (
  <View>
    <Text>
    something goes wrong.
    </Text>
  </View>
)
}

here's the screenshots

enter image description here

[Update] As I reload to clear the error, there's a temporary state which display the error view.

enter image description here

2
  • should we handle the onError also? Commented Aug 21, 2016 at 12:54
  • I'm not sure which properties are required. Commented Aug 21, 2016 at 14:05

1 Answer 1

8

You could use the onError prop as shown below to render a view after an error and also try handling the different WebView errors. renderError can be used to render a view that shows when resolving the WebView errors

onError = (e) => {
    let uri = new URI(this.props.url);
    let host = uri.host();
    let insecureHosts = [-1004, -6, -1202]; //all error codes as displayed on your console 
        if(e){
            //Handles NSURLErrorDomain in iOS and net:ERR_CONNECTION_REFUSED in Android
            if(insecureHosts.indexOf(e.nativeEvent.code) !== -1){
                this.setState({url: `http://${host}`});
            }
            //Handles Name resolution errors by redirecting to Google
            else if(e.nativeEvent.code === -1003 ||  e.nativeEvent.code === -2){
                this.setState({url: `https://www.google.com/#q=${host}`});
            }
        } else {
        //loads the error view only after the resolving of the above errors has failed
            return(<View>
                    <Text>Error occurred while loading the page.</Text>
                  </View>);
            }
};
renderError = (e) => {
    //Renders this view while resolving the error 
    return(<View>
                <ActivityIndicator
                    animating={ true }
                    color='#84888d'
                    size='large'
                    hidesWhenStopped={true}
                    style={{alignItems:'center', justifyContent:'center', padding:30, flex: 1}}/>
            </View>);
};

Remember to install urijs and import it so as to make use of URI.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.