Unable to close modal in Flutter InAppWebView using JavaScript interface

47 views Asked by At

I am trying to implement a Flutter app with a WebView using the InAppWebView plugin. In one of the screens, I have a modal that should be closed when a certain button (btnFechar) is clicked inside the WebView. I am attempting to achieve this by injecting JavaScript code into the WebView and then calling a JavaScript interface function from the Flutter side to close the modal.

However, despite injecting the JavaScript code and setting up the JavaScript interface, the modal does not close when the button is clicked inside the WebView.

Here is a simplified version of my Flutter code:

class ForgotPasswordActivity extends StatefulWidget {
  @override
  _ForgotPasswordActivityState createState() => _ForgotPasswordActivityState();
}

class _ForgotPasswordActivityState extends State<ForgotPasswordActivity> {
  final GlobalKey webViewKey = GlobalKey();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Forgot Password'),
      ),
      body: Container(
        child: InAppWebView(
          key: webViewKey,
          initialUrlRequest: URLRequest(url: WebUri("example.com")),
          initialOptions: InAppWebViewGroupOptions(
            crossPlatform: InAppWebViewOptions(
              javaScriptEnabled: true,
            ),
          ),
          onWebViewCreated: (controller) {
            controller.addJavaScriptHandler(handlerName: 'closeModalClicked', callback: (args) {
              // A função chamada do JavaScript fecha a tela
              Navigator.pop(context);
            });
          },
          onLoadStop: (controller, url) {
            // Quando a página termina de carregar, injetamos o código JavaScript para lidar com os eventos de fechamento do modal
            controller.evaluateJavascript(source: """
              (function(){
                  var button = document.getElementById('btnFechar');
                  var modalBackground = document.getElementById('divMensagem');
                  var closeButton = document.getElementsByClassName('close');

                  button.addEventListener('click', function(){
                      window.flutter_inappwebview.callHandler('closeModalClicked');
                  });                        
                  
                  modalBackground.addEventListener('click', function(){
                      window.flutter_inappwebview.callHandler('closeModalClicked');
                  });
                  
                  closeButton.addEventListener('click', function(){
                      window.flutter_inappwebview.callHandler('closeModalClicked');
                  });
              })()
            """);
          },
        ),
      ),
    );
  }
}

But there is no result of closing the modal

0

There are 0 answers