美文网首页
Flutter WebView 和 JS交互

Flutter WebView 和 JS交互

作者: 小王在努力 | 来源:发表于2020-12-15 14:27 被阅读0次

1、导入库

webview_flutter

2、iOS 单独设置

ios/Runner/Info.plist中添加

<key>io.flutter.embedded_views_preview</key>
<string>YES</string>*

3、Flutter webview的使用

child: WebView(
                key: key,
                javascriptMode: JavascriptMode.unrestricted,
                initialUrl: widget.url,
                onWebViewCreated: (controller) {
                  _controller = controller;
                },
                navigationDelegate: (NavigationRequest request) {
                  var url = request.url;
                  setState(() {
                    isLoading = true; // 开始访问页面,更新状态
                  });
                  return NavigationDecision.navigate;
                },
                onPageFinished: (url) {
                  _controller.evaluateJavascript("document.title").then((result){
                    setState(() {
                      _title = result;
                      isLoading = false; // 页面加载完成,更新状态
                      print("finish");
                    });
                  }
                  );
                },
                javascriptChannels: <JavascriptChannel>[
                  JavascriptChannel(
                      name: "close",
                      onMessageReceived: (JavascriptMessage message) {
                        ATJump.jumpToInvitation();
                      }),
                ].toSet(),
              ),

javascriptMode: JavascriptMode.unrestricted:允许和js交互

4、Flutter 调用JS的方法

4.1、flutter端代码实现

_controller.evaluateJavascript("flutterCallJsMethod('message from Flutter!')”);

4.2、JS端代码实现

function flutterCallJsMethod(message) {
    document.write(message);
}

5、JS 调用Flutter

5.1、flutter端代码实现

javascriptChannels: <JavascriptChannel>[
  JavascriptChannel(
      name: "close",
      onMessageReceived: (JavascriptMessage message) {
        print("========================================= ");
        print(message.message);
        appClose();
      }),
].toSet(),

5.2、JS端安卓设备实现

//安卓方式 JS调用原生
close.postMessage({"key1":"100","key2":"200"});

5.3、JS端iOS设备实现

        //wkWebView JS调用iOS原生
        window.webkit.messageHandlers.close.postMessage({"key1":"100","key2":"200"});
        //UIWebView JS调用iOS原生
<!--   close({"key1":"100","key2":"200"});-->

相关文章

网友评论

      本文标题:Flutter WebView 和 JS交互

      本文链接:https://www.haomeiwen.com/subject/jflwgktx.html