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

10,456

Solution 1

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 comdition here based here and close webview.
                     Like if(e.url.indexOf("end_url") > -1)
                     Then close webview
                     */
                }}
                source={someHTMLFile}
                onLoadEnd={()=>{
                /* add you work that you want to do after loading is done. */
                }}
                ref={(webView) => this.webView = webView}
            />
        </View>
    );
}

Solution 2

Closing WebView is basically equals to un-mounting the component. You can do conditional rendering to mount and un-mount the component. The usual behavior is to open up a Modal which has a WebView inside. When you are done with the WebView you can send a message to react and then close the modal. This will un-mount the modal and WebView.

You can use onMessage prop to communicate between WebView and React-Native.

A function that is invoked when the webview calls window.postMessage. Setting this property will inject a postMessage global into your webview, but will still call pre-existing values of postMessage.

Example

_onMessage = (message) => {
   console.log(message);
}

render() {
  return (<WebView ref={(ref) => { this.webView = ref; }} onMessage={this._onMessage} ..otherProps />);
}

// In your webview inject this code

<script>
  window.postMessage("Sending data from WebView");
</script>
Share:
10,456
Kshitij Mittal
Author by

Kshitij Mittal

Updated on June 04, 2022

Comments

  • Kshitij Mittal
    Kshitij Mittal almost 2 years

    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?