hhstore / blog

My Tech Blog: about Mojo / Rust / Golang / Python / Kotlin / Flutter / VueJS / Blockchain etc.
https://github.com/hhstore/blog/issues
295 stars 24 forks source link

Flutter: Two-way Communication with JS in WebView #289

Open hhstore opened 3 years ago

hhstore commented 3 years ago

related:

hhstore commented 3 years ago

Flutter 在 WebView 中与 JS 双向通信:

浏览器标准 api 支持: window.postMessage()

JSBridge: WebView 在原生 iOS/Android 下

JSBridge: WebView + Flutter

ref:

hhstore commented 3 years ago

使用 webview_flutter:

方式1: javascriptChannels


<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(),
;

方式2: 使用路由委托navigationDelegate拦截url

<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;
          },

flutter 执行 js:

  <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'),
      ),
hhstore commented 3 years ago

1

hhstore commented 3 years ago

1