为您提供2个解决方案:
解决方案1: 推荐
import 'package:flutter/material.dart';
import 'package:flutter_webview_plugin/flutter_webview_plugin.dart';
final Set<JavascriptChannel> jsChannels = [
JavascriptChannel(
name: 'Print',
onMessageReceived: (JavascriptMessage message) {
print('message.message: ${message.message}');
}),
].toSet();
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
routes: {
"/": (_) => WebviewScaffold(
url: Uri.dataFromString(
'<html><button onclick="Print.postMessage(\'test\');">Click me</button></html>',
mimeType: 'text/html')
.toString(),
appBar: new AppBar(title: new Text("Widget webview")),
javascriptChannels: jsChannels,
),
},
);
}
}
I/flutter (22119): message.message: 测试
解决方案2: 如果你想保留你的window.post
。 (也许您想使用iframe
来自另一个平台)
import 'package:flutter/material.dart';
import 'package:flutter_webview_plugin/flutter_webview_plugin.dart';
final Set<JavascriptChannel> jsChannels = [
JavascriptChannel(
name: 'Print',
onMessageReceived: (JavascriptMessage message) {
print('message.message: ${message.message}');
}),
].toSet();
void main() {
final flutterWebviewPlugin = FlutterWebviewPlugin();
flutterWebviewPlugin.onStateChanged.listen((state) async {
if (state.type == WebViewState.finishLoad) {
String script =
'window.addEventListener("message", receiveMessage, false);' +
'function receiveMessage(event) {Print.postMessage(event.data);}';
flutterWebviewPlugin.evalJavascript(script);
}
});
return runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
routes: {
"/": (_) => WebviewScaffold(
url: Uri.dataFromString(
'<html><button onclick="window.postMessage(\'test\', \'*\');">Click me</button></html>',
mimeType: 'text/html')
.toString(),
appBar: new AppBar(title: new Text("Widget webview")),
javascriptChannels: jsChannels,
),
},
);
}
}
I/flutter (22119): message.message: 测试
pubspec.yaml
:
dependencies:
flutter:
sdk: flutter
cupertino_icons: ^0.1.2
flutter_webview_plugin: 0.3.9+1
参考:
- https://github.com/fluttercommunity/flutter_webview_plugin/issues/309 https://github.com/fluttercommunity/flutter_webview_plugin/issues/309
- https://github.com/fluttercommunity/flutter_webview_plugin/pull/457 https://github.com/fluttercommunity/flutter_webview_plugin/pull/457
- https://github.com/fluttercommunity/flutter_webview_plugin/issues/364 https://github.com/fluttercommunity/flutter_webview_plugin/issues/364
- https://github.com/fluttercommunity/flutter_webview_plugin/pull/523/files https://github.com/fluttercommunity/flutter_webview_plugin/pull/523/files
- https://github.com/fluttercommunity/flutter_webview_plugin/issues/305 https://github.com/fluttercommunity/flutter_webview_plugin/issues/305