Search code examples
androidreactjsreact-nativeandroid-webview

How to close webview after the work is done in react native


I am using following code to render a webview:

const someHTMLFile = require('./somefile.html')
render() {
  return (
     <View style={{flex: 1}}>
      <WebView
          style={{flex: 1}}
          source={someHTMLFile}
          ref={( webView ) => this.webView = webView}
      />      
    </View>
  );
}

In this html file, there is a form which is automatically submitted when the webview loads (with some data sent from reactnative part of code) and in the end, the file is redirected to a specific url, where some processing is done (on the send data), and right now, it returns nothing. So the screen goes blank.

So, at this point, I want to close the webview and take the user back to my reactnative app.. So, how can I do that? any suggestions?


Solution

  • Webview have onNavigationStateChange props which will give a foundation when webview loading starts or ends.

    Therefore you can use these props to check current state or the current URL of webview and put some condition to close the webview.

    render() {
        return (
            <View style={{flex: 1}}>
                <WebView
                    style={{flex: 1}}
                    onNavigationStateChange={(e) => {
                        console.warn("current state is ", JSON.stringify(e, null, 2));
                        /** put your condition here to close webview.
                         Like if(e.url.indexOf("end_url") > -1)
                         Then close webview
                         */
                    }}
                    source={someHTMLFile}
                    onLoadEnd={()=>{
                    /* add your work that you want to do after loading is done. */
                    }}
                    ref={(webView) => this.webView = webView}
                />
            </View>
        );
    }