Open hhstore opened 3 years ago
https://juejin.cn/post/6844903811488677901
flutter
中 JavascriptChannel
中的 name
, 要与 JS
中的name.postMessage()
相对应
<button onclick="callFlutter()">callFlutter</button>
function callFlutter(){
Toast.postMessage("JS调用了Flutter");
}
JavascriptChannel _alertJavascriptChannel(BuildContext context) {
return JavascriptChannel(
name: 'Toast',
onMessageReceived: (JavascriptMessage message) {
showToast(message.message);
});
}
WebView(
javascriptChannels: <JavascriptChannel>[
_alertJavascriptChannel(context),
].toSet(),
;
<button onclick="callFlutter()">callFlutter</button>
function callFlutter(){
/*约定的url协议为:js://webview?arg1=111&arg2=222*/
document.location = "js://webview?arg1=111&args2=222";
}
navigationDelegate: (NavigationRequest request) {
if (request.url.startsWith('js://webview')) {
showToast('JS调用了Flutter By navigationDelegate');
print('blocking navigation to $request}');
return NavigationDecision.prevent;
}
print('allowing navigation to $request');
return NavigationDecision.navigate;
},
<p id="p1" style="visibility:hidden;">
Flutter 调用了 JS.
Flutter 调用了 JS.
Flutter 调用了 JS.
</p>
function callJS(message){
document.getElementById("p1").style.visibility = message;
}
onWebViewCreated: (WebViewController webViewController) {
_controller = webViewController;
},
······
floatingActionButton: FloatingActionButton(
onPressed: () {
_controller
?.evaluateJavascript('callJS("visible")')
?.then((result) {
// You can handle JS result here.
});
},
child: Text('call JS'),
),
1
1
related: