flutter webview_flutter 与JavaScript交互

自作多情 提交于 2020-04-06 13:51:44

webview_flutter与交互
1.通过拦截url的方式

      navigationDelegate: (NavigationRequest navigation) {
        String url = navigation.url;

        if (url.contains("micrpayclient://")) {
          //之前定义的micrpayclient保持不变
          String lStrig = 'micrpayclient://url=';
          int index = url.indexOf(lStrig);
          String subString = url.substring(index + lStrig.length);
          try {
            var dUrl = Uri.decodeComponent(subString);
            launch(dUrl);
          } catch (error) {
            print(error);
          }
          return NavigationDecision.prevent;
        }
        return NavigationDecision.navigate;
      },

2.通过JavascriptChannel来实现

 WebView(
      initialUrl: widget.url,
      userAgent:
          "Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Mobile Safari/537.36",
      navigationDelegate: listenWebview,
      javascriptMode: JavascriptMode.unrestricted,
      onWebViewCreated: (vc) {
        _controller = vc;
        print('webviewUrl = ${widget.url}');
      },
      onPageFinished: (String value) {
        print('webviewUrl = $value');
        _handleNaviData();
      },
      javascriptChannels: [
        JavascriptChannel(
        name: 'tudouApp',//handleName
        onMessageReceived: (JavascriptMessage message) {
          print(message.message);
          //接收到js返回的数据
          //自定义处理
        }),
        JavascriptChannel(
        name: 'JSHandle',//handleName
        onMessageReceived: (JavascriptMessage message) {
          print(message.message);
          //接收到js返回的数据
          //自定义处理
        }),
      ].toSet(),
    )
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!