I am trying to add going back on webview when the android backbutton was pressed and I still couldn't manage to make it work.
This is my code:
<WebView
ref={WEBVIEW_REF}
source={source}
domStorageEnabled={true}
onNavigationStateChange={this.onNavigationStateChange}
/>
componentDidMount() {
BackAndroid.addEventListener('hardwareBackPress', function() {
if(this.state.backButtonEnabled) {
this.refs[WEBVIEW_REF].goBack();
return true;
}
});
};
onNavigationStateChange = (navState) => {
this.setState({
backButtonEnabled: navState.canGoBack,
});
};
With the code above I'm getting the error undefined is not an object this.state.backButtonEnabled (which is set in the state).
Than I just wanted to see if the goBack works so I removed the if statement and than I was getting the error undefined is not an object this.refs[WEBVIEW_REF].
What is the best solution for this?
1) Bind your handler 2) Do not forget to removeListener on unmount.
In case of webview in react native, app exit when pressing the back button of mobile by default. If you want to go the previous page when pressing the back button then you need to implement the "goback" function of react-native webview.
You can see the Step 5 : Handle Mobile Back Button section of this article.
Here's a solution with Typescript and
useRef
anduseEffect
hooks.I didn't use
canGoBack
, but it seems to work regardless.Wanted to add a full example in case it helps anyone:
This might help someone as the above solutions didn't solve my problem....