作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有一个 flutter 代码片段,它从我的 iframe 页面监听 postMessage。
(flutter_webview_plugin: ^0.3.9+1)
flutterWebviewPlugin.onStateChanged.listen((viewState) async {
String script = 'window.addEventListener("message", receiveMessage, false);' +
'function receiveMessage(event) {console.log(\'receiving data from child , data as follows: \',event.data)}';
flutterWebviewPlugin.evalJavascript(script);
}
window.addEventListener( "message" , function( event )
{
else if( event.data.indexOf( "camera" ) >= 0 )
{
//Trigger Camera Function
最佳答案
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: test
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: test
pubspec.yaml
:
dependencies:
flutter:
sdk: flutter
cupertino_icons: ^0.1.2
flutter_webview_plugin: 0.3.9+1
关于Flutter 如何从 flutterWebviewPlugin.evalJavascript (addEventListener) 中检索 javascript 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58985946/
我是一名优秀的程序员,十分优秀!