0

I am trying to load an HTML form in a webview that has some callbacks on button clicks which I am trying to handle in a javascript handler but are not getting invoked.

Library used

flutter_inappwebview: ^5.7.1

This is how I defined the webview.

InAppWebView(
      initialOptions: InAppWebViewGroupOptions(
          crossPlatform: InAppWebViewOptions(
            useShouldOverrideUrlLoading: true,
            mediaPlaybackRequiresUserGesture: false,
          ),
          android: AndroidInAppWebViewOptions(
            useHybridComposition: true,
          ),
          ios: IOSInAppWebViewOptions(
            allowsInlineMediaPlayback: true,
          )
      ),
      initialUrlRequest: URLRequest(
          url: Uri.dataFromString(
            'about:blank',
            mimeType: 'text/html',
          )),
      onWebViewCreated: (controller) {
        controller.addJavaScriptHandler(
            handlerName: 'showToast',
            callback: (data) {
              AppUtils.showMessage(data);
              print('data -$data');
            });
        
        setState((){
          _controller = controller;
        });
        loadForm();
      },
      onLoadStop: (controller,uri){
      },
      onConsoleMessage: (controller, message) {
        print('on Console message - $message');
      },
    )

And in load form I am using an html page which looks like

 <!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Test</title>
</head>

  <script>
    isAppReady = false;
    window.addEventListener("flutterInAppWebViewPlatformReady", function (event) {
        isAppReady = true;
    });
    
   function buttonClick() {
    if (isAppReady) {
        window.flutter_inappwebview.callHandler('showToast', 'result');
    }
  }



</script>

<body>
     <button onclick="buttonClick()" type="button">Show</button>
</body>


</html>

Now The event listener is never invoked hence the boolean value is app ready and is not changed. Any help regarding why it is not getting invoked is appreciated

1
  • do you fixed this issue Commented Oct 11, 2023 at 15:33

2 Answers 2

1

Here is a simple working example using the current latest plugin version 6 (6.0.0-beta.17):

import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_inappwebview/flutter_inappwebview.dart';

Future main() async {
  WidgetsFlutterBinding.ensureInitialized();
  if (!kIsWeb &&
      kDebugMode &&
      defaultTargetPlatform == TargetPlatform.android) {
    await InAppWebViewController.setWebContentsDebuggingEnabled(kDebugMode);
  }
  runApp(const MaterialApp(home: MyApp()));
}

class MyApp extends StatefulWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  final GlobalKey webViewKey = GlobalKey();

  InAppWebViewController? webViewController;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: const Text("InAppWebView test"),
        ),
        body: Column(children: <Widget>[
          Expanded(
            child: InAppWebView(
              key: webViewKey,
              initialData: InAppWebViewInitialData(data: """
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Test</title>
</head>
<script>
  isAppReady = false;
  window.addEventListener("flutterInAppWebViewPlatformReady", function (event) {
    isAppReady = true;
  });

  function buttonClick() {
    if (isAppReady) {
      window.flutter_inappwebview.callHandler('showToast', 'result');
    }
  }
</script>
<body>
  <button onclick="buttonClick()" type="button">Show</button>
</body>
</html>
"""),
              onWebViewCreated: (controller) {
                webViewController = controller;

                controller.addJavaScriptHandler(
                    handlerName: 'showToast',
                    callback: (arguments) {
                      final String data = arguments[0];
                      ScaffoldMessenger.of(context).showSnackBar(SnackBar(
                        content: Text(data),
                        duration: const Duration(seconds: 1),
                      ));
                    });
              },
            ),
          ),
        ]));
  }
}

InAppWebView example

Sign up to request clarification or add additional context in comments.

1 Comment

it is not work while the site host.can you help me. it is very urgent for me
0

You can use the flutter_html package. And load the HTML code as a string

flutter_html 👍

2 Comments

But is it possible to pass data from the html to the flutter code with this plugin
Yes, we can open as file and store to string link

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.