【问题标题】:Flutter webview with custom javascriptInterfaceAdapter or invoke JS using webview controller使用自定义 javascriptInterfaceAdapter Flutter webview 或使用 webview 控制器调用 JS
【发布时间】:2022-01-20 01:42:33
【问题描述】:

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

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

JavascriptAdapter 类中有几个@JavascriptInterface 函数。举例

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

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

var strMacAddress = AndroidFunctions.getMACAddress();

现在我想在颤振上实现这个目标。为此,我正在使用flutter inAppWebview 插件。

另外,我试过flutter_webview,WKWebview。

【问题讨论】:

  • 在pub.dev上尝试使用webview_flutter官方插件
  • 尝试过但无法通过函数。

标签: javascript flutter webview flutter-web flutter-inappwebview


【解决方案1】:

您可以从 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}
                    },
                  ),
                ),
              ]))),
    );
  }
}

【讨论】:

    【解决方案2】:

    请查看this InAppWebView 的文档。

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

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

    【讨论】:

      猜你喜欢
      • 2020-03-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多