首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >使用自定义javascriptInterfaceAdapter或使用webview控制器调用JS

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

Stack Overflow用户
提问于 2021-12-17 03:01:36
回答 2查看 1.7K关注 0票数 1

我有一个用addJavascriptInterface在安道尔webview中执行的旧java项目。

代码语言:javascript
运行
复制
mWebView.addJavascriptInterface(new JavascriptAdapter(), "AndroidFunctions");

JavascriptAdapter类中有几个@JavascriptInterface函数。作为例子

代码语言:javascript
运行
复制
class JavascriptAdapter {
    @JavascriptInterface
    getMacAddress(){
        DeviceInfo deviceInfo = new DeviceInfo(activity);
        return deviceInfo.getMacAddress();
  }
}

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

var strMacAddress = AndroidFunctions.getMACAddress();

现在,我想实现这件事的颤栗。为此,我使用的是颤振inAppWebview插件。

另外,我还试过flutter_webview,WKWebview。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2021-12-17 16:11:39

请查看文档中的InAppWebView。

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

代码语言:javascript
运行
复制
<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>
票数 1
EN

Stack Overflow用户

发布于 2021-12-18 01:07:44

您可以从google查看此Webview。

代码语言:javascript
运行
复制
chrome://inspect/#devices

不要忘记在您的flutter_inappwebview: ^5.3.2中添加pubspec.yaml

答案已经在这个链接中给出了,我刚才添加了这个答案,以便快速查看它。

代码语言:javascript
运行
复制
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}
                    },
                  ),
                ),
              ]))),
    );
  }
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/70387950

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档