React Native WebView Loading Error Handling
19,199
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
.
Author by
Klyment
Updated on June 08, 2022Comments
-
Klyment almost 2 years
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
[Update] As I reload to clear the error, there's a temporary state which display the error view.