webview_flutter与js互动

     由于要求在webview_flutter与网页JS相互调用,这里做个简单说明

//前面要定义
WebViewController _webViewController;


 //js调用flutter关键地方
  JavascriptChannel _setScanBarcode(BuildContext context) {
    return JavascriptChannel(
        name: 'ScanBarcode',
        onMessageReceived: (JavascriptMessage message) async {
          print(message.message);         
        });
  }
  
_captionWEbview() {
    return WebView(
                initialUrl: url,
                //JS执行模式 是否允许JS执行
                javascriptMode: JavascriptMode.unrestricted,
                javascriptChannels: [
                    _setScanBarcode(context),
                ].toSet(),
                onWebViewCreated: (WebViewController controller) {
                  _webViewController = controller;
                },
              );
  }


//这里是flutter调用js,可以放在按钮事件里面
_webViewController.evaluateJavascript("SCANRsult('"+barcode+"')");


//这里是html里面的js
if(window.hasOwnProperty('ScanBarcode')){
                    window.ScanBarcode.postMessage("调用摄像头");  
                } 

 

webview_flutter与js互动_第1张图片

 

你可能感兴趣的:(flutter)