flutter webview 調(diào)用js

目標(biāo)

  • 實現(xiàn)flutter 調(diào)用 js
  • Js 返回結(jié)果

項目實現(xiàn)

call_js_page.dart通過webview_flutter_plus 來加載 index.html,使用js交互。

index.html

<html>
<head>
</head>
<body>
<h1 id="title">call js</h1>
<script type="text/javascript">
    function fromFlutter(title){
      document.getElementById("title").innerHTML = title;
      sendBack();
    }
    function sendBack() {
       messageHandler.postMessage("Hello from JS");
    }
</script>
</body>
</html>

js塊中有兩個方法

  • fromFlutter:此方法在flutter調(diào)用并傳遞title參數(shù)
  • sendBack:此方法返回數(shù)據(jù)給flutter

call_js_page.dart

class CallJsPage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return _CallJsPageState();
  }
}

class _CallJsPageState extends State<CallJsPage> {
  WebViewPlusController? _controller;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("flutter web call js"),
      ),
      body: WebViewPlus(
        onWebViewCreated: (controller) {
          _controller = controller;
          controller.loadUrl('assets/index.html');
        },
        javascriptMode: JavascriptMode.unrestricted,
        javascriptChannels: {
          JavascriptChannel(
              name: "messageHandler",
              onMessageReceived: (JavascriptMessage message) {
                print(message);
                ScaffoldMessenger.of(context).showSnackBar(SnackBar(
                  content: Text(message.message),
                ));
              })
        },
      ),
      floatingActionButton: FloatingActionButton(
        child: const Icon(Icons.add),
        onPressed: () {
          _controller?.webViewController
              .evaluateJavascript("fromFlutter('from flutter')");
        },
      ),
    );
  }
}
怎樣調(diào)用index.htmlfromFlutter方法

通過_controller?.webViewController.evaluateJavascript 方法

_controller?.webViewController
              .evaluateJavascript("fromFlutter('from flutter')");
怎樣接收index.html頁面的數(shù)據(jù)

通過JavascriptChannel 來接收,注意下name 要一致。

 javascriptChannels: {
          JavascriptChannel(
              name: "messageHandler",
              onMessageReceived: (JavascriptMessage message) {
                print(message);
                ScaffoldMessenger.of(context).showSnackBar(SnackBar(
                  content: Text(message.message),
                ));
              })
        },

效果圖

flutter_web_call_js.gif

源碼

webview_flutter_plus-call-js

參考

https://pub.dev/packages/webview_flutter_plus

https://medium.com/flutter/the-power-of-webviews-in-flutter-a56234b57df2

https://medium.com/flutter-community/js-native-communication-bridge-in-flutter-f94b65913df1

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容