Recently, the business needs to use webview in flutter for embedded H5 display. At this time, it needs to involve the communication between H5 and flutter. Such as sending a message or H5 calling Flutter's camera, etc.
webview selection
Here we use the officially maintained plugin webview_flutter
How to communicate?
When webview is initialized, it needs to register a global method in the container for H5 to call
WebView(
initialUrl: 'https://flutter.dev',
javascriptMode: JavascriptMode.unrestricted,
javascriptChannels: <JavascriptChannel>{
_toasterJavascriptChannel(context),
}
....
....
)
JavascriptChannel _toasterJavascriptChannel(BuildContext context) {
return JavascriptChannel(
name: 'Toaster',//注册一个名字为Toaster的全局js方法
onMessageReceived: (JavascriptMessage message) {
//处理业务的代码逻辑
print(message)
});
}
H5 send message to flutter
H5 sends messages in the form of xxxx.postMessage. Note that the object here needs to be JSON.stringify
Toaster.postMessage(
JSON.stringify({
name: 'tom',
age: 12
})
);
flutter send message to H5
Need to call runJavascript
method, we can declare a global windows
method in H5
window.globalCallback = function (data) {
console.log(data)
};
Flutter is sent in the form of runJavascript
WebViewController!.runJavascript('globalCallback(123)');//如果是对象也需要json.encode序列化
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。