我有一个html文件,我正在使用flutter_webview_plugin在Flutter webview中加载它。我正在使用evalJavascript来调用javascript代码中的函数,即flutter(dart)->js。然而,我也需要一些方法来将一些东西传回flutter(dart)层,即js->flutter(dart)。
我已经尝试使用- webkit.messageHandlers.native - window.native来支持这两个平台(Android,iOS),检查它们在JS中是否可用。但是,这些都是未定义的。使用以下代码在JS中获取本机处理程序的实例。
typeof webkit !== 'undefined' ? webkit.messageHandlers.native :
window.native;
即使我使用它获取实例并发布消息,也不确定如何在flutter(dart)层中处理它。我可能需要使用平台通道。我不确定我是否走对了方向。
有什么方法可以让我做到这一点吗?我已经评估了interactive_webview插件。它在Android上运行得很好。但是,它有迅速的版本问题,不想继续下去。
任何帮助都将不胜感激。
发布于 2021-01-04 01:03:01
使用flutter_inappwebview包的Javascript回调的完整代码示例:
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter_inappwebview/flutter_inappwebview.dart';
Future main() async {
WidgetsFlutterBinding.ensureInitialized();
runApp(new MyApp());
}
class MyApp extends StatefulWidget {
@override
_MyAppState createState() => new _MyAppState();
}
class _MyAppState extends State<MyApp> {
InAppWebViewController _webViewController;
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: const Text('InAppWebView Example'),
),
body: Container(
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 (Channels) TEST</h1>
<button id='test' onclick="window.flutter_inappwebview.callHandler('testFunc');">Test</button>
<button id='testargs' onclick="window.flutter_inappwebview.callHandler('testFuncArgs', 1);">Test with Args</button>
<button id='testreturn' onclick="window.flutter_inappwebview.callHandler('testFuncReturn').then(function(result) { alert(result);});">Test Return</button>
</body>
</html>
"""),
initialOptions: InAppWebViewGroupOptions(
crossPlatform: InAppWebViewOptions(
debuggingEnabled: true,
)),
onWebViewCreated: (InAppWebViewController controller) {
_webViewController = controller;
_webViewController.addJavaScriptHandler(
handlerName: 'testFunc',
callback: (args) {
print(args);
});
_webViewController.addJavaScriptHandler(
handlerName: 'testFuncArgs',
callback: (args) {
print(args);
});
_webViewController.addJavaScriptHandler(
handlerName: 'testFuncReturn',
callback: (args) {
print(args);
return '2';
});
},
onConsoleMessage: (controller, consoleMessage) {
print(consoleMessage);
},
),
),
])),
),
);
}
}
https://stackoverflow.com/questions/53689662
复制相似问题