flutter_inappwebview icon indicating copy to clipboard operation
flutter_inappwebview copied to clipboard

Didnt get js response from live website

Open mfkk16 opened this issue 8 months ago • 3 comments

Technology Version
Flutter version 3.13.6
Plugin version ^6.0.0-beta.25
Android version 13
iOS version 12
macOS version
Xcode version

Device information: All

I trying to fetch the response from the website, for that im using flutter_inappwebview: ^6.0.0-beta.25 . in the web side I added Javascript code. but I didn't get response in the flutter app. If I call window.flutter_inappwebview.callHandler('FlutterFunction', "got success message"); without window.addEventListener I got this error "Cannot read properties of undefined (reading 'callHandler')". Please help me to fix this.


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,
              initialUrlRequest: URLRequest(url: WebUri("https://mfkk16.github.io/kkmf-resume/")),
              onWebViewCreated: (controller) {
                webViewController = controller;
                controller.addJavaScriptHandler(
                    handlerName: 'FlutterFunction',
                    callback: (arguments) {
                      ScaffoldMessenger.of(context).showSnackBar(SnackBar(
                        content: Text(arguments[0]),
                        duration: const Duration(seconds: 1),
                      ));
                    });

              },
            ),
          ),
        ]));
  }
}

My Web site code

<!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>
    function buttonClick() {
        console.log("button click");
        try {
            window.addEventListener("flutterInAppWebViewPlatformReady", function (event) {
                window.flutter_inappwebview.callHandler('FlutterFunction', "got success message");
                console.log("success");
            });
        } catch (error) {
            console.log(error);
        }
    }
</script>

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

</html>

mfkk16 avatar Oct 11 '23 19:10 mfkk16