使用自定义 javascriptInterfaceAdapter 的 Flutter webview 或使用 webview 控制器调用 JS

Flutter webview with custom javascriptInterfaceAdapter or invoke JS using webview controller

我有一个旧的 java 项目,它使用 addJavascriptInterface 在 andorid webview 中执行

mWebView.addJavascriptInterface(new JavascriptAdapter(), "AndroidFunctions");

JavascriptAdapter class 中有几个 @JavascriptInterface 函数。例如

class JavascriptAdapter {
    @JavascriptInterface
    getMacAddress(){
        DeviceInfo deviceInfo = new DeviceInfo(activity);
        return deviceInfo.getMacAddress();
  }
}

现在在 android 应用程序中打开 webview 后,使用 JS 我们可以像这样访问该功能 -

var strMacAddress = AndroidFunctions.getMACAddress();

现在想在flutter上实现这个东西。为此,我正在使用 flutter inAppWebview 插件。

另外,我试过flutter_webview,WKWebview.

请查看 InAppWebView 的 this 文档。

JavScriptInterface 通常用于从 webview 调用本地方法。我假设该网页调用该方法,因此,您必须 return 文档中显示的 Mac 地址。但是您需要通过将此示例(在文档中提供)添加到您的网页源来更改调用 flutter 方法的方式。

<script>
        window.addEventListener("flutterInAppWebViewPlatformReady", function(event) {
            window.flutter_inappwebview.callHandler('handlerFoo')
              .then(function(result) {
                // print to the console the data coming
                // from the Flutter side.
                console.log(JSON.stringify(result));
                
                window.flutter_inappwebview
                  .callHandler('handlerFooWithArgs', 1, true, ['bar', 5], {foo: 'baz'}, result);
            });
        });
    </script>

您可以从 google chrome.

检查此 Webview
chrome://inspect/#devices

并且不要忘记在 pubspec.yaml

中添加 flutter_inappwebview: ^5.3.2

这里已经给出了答案link 我刚刚添加了快速浏览 SO。

import 'dart:async';
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter_inappwebview/flutter_inappwebview.dart';

Future main() async {
  WidgetsFlutterBinding.ensureInitialized();

  if (Platform.isAndroid) {
    await AndroidInAppWebViewController.setWebContentsDebuggingEnabled(true);
  }
  
  runApp(new MyApp());
}

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => new _MyAppState();
}

class _MyAppState extends State<MyApp> {

  InAppWebViewGroupOptions options = InAppWebViewGroupOptions(
      android: AndroidInAppWebViewOptions(
        useHybridComposition: true,
      ),);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
          appBar: AppBar(title: Text("JavaScript Handlers")),
          body: SafeArea(
              child: Column(children: <Widget>[
                Expanded(
                  child: InAppWebView(
                    initialData: InAppWebViewInitialData(
                        data: """
<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    </head>
    <body>
        <h1>JavaScript Handlers</h1>
        <script>
            window.addEventListener("flutterInAppWebViewPlatformReady", function(event) {
                window.flutter_inappwebview.callHandler('handlerFoo')
                  .then(function(result) {
                    // print to the console the data coming
                    // from the Flutter side.
                    console.log(JSON.stringify(result));
                    
                    window.flutter_inappwebview
                      .callHandler('handlerFooWithArgs', 1, true, ['bar', 5], {foo: 'baz'}, result);
                });
            });
        </script>
    </body>
</html>
                      """
                    ),
                    initialOptions: options,
                    onWebViewCreated: (controller) {
                      controller.addJavaScriptHandler(handlerName: 'handlerFoo', callback: (args) {
                        // return data to the JavaScript side!
                        return {
                          'bar': 'bar_value', 'baz': 'baz_value'
                        };
                      });

                      controller.addJavaScriptHandler(handlerName: 'handlerFooWithArgs', callback: (args) {
                        print(args);
                        // it will print: [1, true, [bar, 5], {foo: baz}, {bar: bar_value, baz: baz_value}]
                      });
                    },
                    onConsoleMessage: (controller, consoleMessage) {
                      print(consoleMessage);
                      // it will print: {message: {"bar":"bar_value","baz":"baz_value"}, messageLevel: 1}
                    },
                  ),
                ),
              ]))),
    );
  }
}