Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Native WebView App not exit on pressing back button

React Native WebView App not exit on pressing back button after setting Go back functionality on back button pressed. I want go back functionality on pressing back button when webview is not on home page and when webview is on home page then exit the app.

export default class WebView extends Component {

    constructor (props) {
        super(props);
        this.WEBVIEW_REF = React.createRef();
    }

    componentDidMount() {
        BackHandler.addEventListener('hardwareBackPress', this.handleBackButton);
    }

    componentWillUnmount() {
      BackHandler.removeEventListener('hardwareBackPress', this.handleBackButton);
    }

    handleBackButton = ()=>{
       this.WEBVIEW_REF.current.goBack();
       return true;
    }

    onNavigationStateChange(navState) {
      this.setState({
        canGoBack: navState.canGoBack
      });
    }


      render(){
        return (
          <WebView
            source={{ uri: 'https://stackoverflow.com' }}
            ref={this.WEBVIEW_REF}
            onNavigationStateChange={this.onNavigationStateChange.bind(this)}

          />
        );
      }
    }
like image 602
beginner Avatar asked Apr 08 '20 14:04

beginner


1 Answers

Since you are managing the state of canGoBack inside onNavigationStateChange function, Change your handleBackButton function as below,

handleBackButton = () => {
  if (this.state.canGoBack) {
    this.WEBVIEW_REF.current.goBack();
    return true;
  }
}

Check below complete example

import React, { Component } from "react";
import { BackHandler } from "react-native";
import { WebView } from "react-native-webview";

export default class App extends Component {
  WEBVIEW_REF = React.createRef();

  state = {
    canGoBack: false,
  };

  componentDidMount() {
    BackHandler.addEventListener("hardwareBackPress", this.handleBackButton);
  }

  componentWillUnmount() {
    BackHandler.removeEventListener("hardwareBackPress", this.handleBackButton);
  }

  handleBackButton = () => {
    if (this.state.canGoBack) {
      this.WEBVIEW_REF.current.goBack();
      return true;
    }
  };

  onNavigationStateChange = (navState) => {
    this.setState({
      canGoBack: navState.canGoBack,
    });
  };

  render() {
    return (
      <WebView
        source={{ uri: "https://stackoverflow.com" }}
        ref={this.WEBVIEW_REF}
        onNavigationStateChange={this.onNavigationStateChange}
      />
    );
  }
}

Hope this helps you. Feel free for doubts.

like image 136
SDushan Avatar answered Oct 26 '22 05:10

SDushan