繁体   English   中英

Flutter InappWebview 未调用 javascript 回调 function

[英]Flutter InappWebview is not calling the javascript callback function

我正在尝试在 webview 中加载一个 HTML 表单,该表单对按钮点击有一些回调,我试图在 javascript 处理程序中处理但没有被调用。

使用的库

flutter_inappwebview: ^5.7.1

这就是我定义 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');
      },
    )

在加载表单中,我使用的是 html 页面,它看起来像

 <!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>

现在永远不会调用事件侦听器,因此 boolean 值已准备好应用程序并且未更改。 任何关于为什么它没有被调用的帮助表示赞赏

您可以使用 flutter_html package。并将 HTML 代码作为字符串加载

flutter_html

这是一个使用当前最新插件版本 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 示例

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM