androidiosflutterwebviewnavigation

How to close a WebView and go back to the previous screen in a Flutter app?


I'm using a WebView in my Flutter app to display a webpage. When the user taps a button or finishes an action inside the WebView, I want to automatically close the WebView and return to the previous Flutter screen.

How can I detect that event and pop the WebView screen?


Solution

  • If you are using html you can do something like
    <button onclick="CloseWebView.postMessage('close')">Close WebView</button>
    inside your HTML/React and catch it inside your webview.

    controller = WebViewController()
          ..setJavaScriptMode(JavaScriptMode.unrestricted)
          ..addJavaScriptChannel(
            'CloseWebView',
            onMessageReceived: (JavaScriptMessage message) {
              // Pop the web-view
              Navigator.pop(context);
            },
          )
          ..loadRequest(Uri.parse('https://my-portfolio.com'));
    

    using the

    onMessageReceived
    

    parameter you can listen to the javascript inside your webview and can customise it in any way you like.