Flutter Webview 与 Javascript 的双向通信

问题描述 投票:0回答:7

我有一个 html 文件,正在使用 flutter_webview_plugin 在 Flutter webview 中加载。我正在使用 evalJavascript 在我的 javascript 代码中调用函数,这意味着 flutter(dart)->js。但是,我还需要某种方法来与 flutter(dart) 层进行通信,即 js->flutter(dart)。

我尝试过使用 - webkit.messageHandlers.native - 窗口.native 支持两个平台(Android、iOS),检查这些平台是否在 JS 中可用。但是,这些都是未定义的。使用以下代码在 JS 中获取本机处理程序的实例。

typeof webkit !== 'undefined' ? webkit.messageHandlers.native : 
window.native;

即使我获得该实例并使用它发布消息,也不知道如何在 flutter(dart) 层中处理它。我可能需要使用平台渠道。不确定我的方向是否正确。

有什么办法可以做到这一点吗?我已经评估了 Interactive_webview 插件。它在 Android 上运行良好。但是,它存在快速版本控制问题,并且不想进一步继续下去。

如有任何帮助,我们将不胜感激。

javascript webview dart flutter
7个回答
65
投票

这里是一个从Javascript代码到flutter的通信示例。

在 Flutter 中构建你的 WebView,如下所示:

WebView(
              initialUrl: url,
              javascriptMode: JavascriptMode.unrestricted,
              javascriptChannels: Set.from([
                JavascriptChannel(
                    name: 'Print',
                    onMessageReceived: (JavascriptMessage message) {
                      //This is where you receive message from 
                      //javascript code and handle in Flutter/Dart
                      //like here, the message is just being printed
                      //in Run/LogCat window of android studio
                      print(message.message);
                    })
              ]),
              onWebViewCreated: (WebViewController w) {
                webViewController = w;
              },
            )

并在您的 HTML 文件中:

<script type='text/javascript'>
    Print.postMessage('Hello World being called from Javascript code');
</script>

当您运行此代码时,您将能够在 android studio 的 LogCat/Run 窗口中看到日志“Hello World being call from Javascript code”。


25
投票

你可以尝试我的插件flutter_inappbrowser编辑:它已重命名为flutter_inappwebview)并使用

addJavaScriptHandler({@required String handlerName, @required JavaScriptHandlerCallback callback})
方法(查看更多这里)。

下面提供了一个示例。 在颤振方面:

...

child: InAppWebView(
  initialFile: "assets/index.html",
  initialHeaders: {},
  initialOptions: InAppWebViewWidgetOptions(
    inAppWebViewOptions: InAppWebViewOptions(
        debuggingEnabled: true,
    )
  ),
  onWebViewCreated: (InAppWebViewController controller) {
    webView = controller;

    controller.addJavaScriptHandler(handlerName: "mySum", callback: (args) {
      // Here you receive all the arguments from the JavaScript side 
      // that is a List<dynamic>
      print("From the JavaScript side:");
      print(args);
      return args.reduce((curr, next) => curr + next);
    });
  },
  onLoadStart: (InAppWebViewController controller, String url) {

  },
  onLoadStop: (InAppWebViewController controller, String url) {

  },
  onConsoleMessage: (InAppWebViewController controller, ConsoleMessage consoleMessage) {
    print("console message: ${consoleMessage.message}");
  },
),

...

在 JavaScript 端(例如 asset 文件夹内的本地文件

assets/index.html
):

<!doctype html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
        <meta http-equiv="X-UA-Compatible" content="ie=edge">
        <title>Flutter InAppBrowser</title>
        
        ...
        
    </head>
    <body>

        ...

        <script>
           // In order to call window.flutter_inappwebview.callHandler(handlerName <String>, ...args) 
           // properly, you need to wait and listen the JavaScript event flutterInAppWebViewPlatformReady. 
           // This event will be dispatched as soon as the platform (Android or iOS) is ready to handle the callHandler method. 
           window.addEventListener("flutterInAppWebViewPlatformReady", function(event) {
             // call flutter handler with name 'mySum' and pass one or more arguments
             window.flutter_inappwebview.callHandler('mySum', 12, 2, 50).then(function(result) {
               // get result from Flutter side. It will be the number 64.
               console.log(result);
             });
           });
        </script>
    </body>
</html>

在 Android Studio 日志上,您将得到:

I/flutter (20436): From JavaScript side:
I/flutter (20436): [12, 2, 50]
I/flutter (20436): console message: 64

13
投票

我想告诉大家如何从flutter WebView向JS发送消息:

  1. 在 JS 代码中,您需要将需要触发的函数绑定到窗口
const function = () => alert('hello from JS');
window.function = function;
  1. 在 WebView 小部件实现中的代码中,您需要声明像这样的 onWebViewCreated 方法
WebView(
  onWebViewCreated: (WebViewController controller) {},
  initialUrl: 'https://url.com',
  javascriptMode: JavascriptMode.unrestricted,
)
  1. 在类小部件中声明
    var _webViewController;
class App extends State<MyApp> {
  final _webViewController;
}
  1. onWebViewCreated中写入这段代码
onWebViewCreated: (WebViewController controller) {
    _webViewController = controller;
},

然后你可以运行这样的代码:

class App extends StatelessWidget {
  var _webViewController;

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      home: Scaffold(
        body: WebView(
          onWebViewCreated: (WebViewController controller) {
            _webViewController = controller;
          },
          initialUrl: 'https://url.com',
          javascriptMode: JavascriptMode.unrestricted,
        ),
        floatingActionButton: FloatingActionButton(
          onPressed: () {
            // When you click at this button youll run js code and youll see alert
            _webViewController
                .evaluateJavascript('window.function ()');
          },
          child: Icon(Icons.add),
          backgroundColor: Colors.green,
        ),
      ),
    );
  }
}

但是如果我们想将这个

_webViewController
实例共享给其他小部件(例如抽屉)怎么办?
在这种情况下,我决定实现
Singleton pattern
并将
_webViewController
实例存储在其中。
所以
单例类

class Singleton {
  WebViewController webViewController;

  static final Singleton _singleton = new Singleton._internal();

  static Singleton get instance => _singleton;

  factory Singleton(WebViewController webViewController) {
    _singleton.webViewController = webViewController;
    return _singleton;
  }

  Singleton._internal();
}

然后

onWebViewCreated: (WebViewController controller) {
  var singleton = new Singleton(controller);
},

最后在我们的抽屉小部件中(在这里您可以使用任何您想要的小部件)

class EndDrawer extends StatelessWidget {
  final singleton = Singleton.instance;

  @override
  Widget build(BuildContext context) {
    return Drawer(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.end,
        children: <Widget>[
          SizedBox(
              width: 200,
              child: FlatButton(
                onPressed: () {
                  singleton.webViewController.evaluateJavascript('window.function()');
                  Navigator.pop(context); // exit drawer
                },
                child: Row(
                  children: <Widget>[
                    Icon(
                      Icons.exit_to_app,
                      color: Colors.redAccent,
                    ),
                    SizedBox(
                      width: 30,
                    ),
                    Text(
                      'Exit',
                      style: TextStyle(color: Colors.blueAccent, fontSize: 20),
                    ),
                  ],
                ),
              )),
        ],
      ),
    );
  }
}

如果您想从 JS 代码接收消息到您的 flutter 应用程序,您需要:

  1. 在你的js代码中
window.CHANNEL_NAME.postMessage('Hello from JS');
  1. 在你的 flutter 代码中。
    当您运行 JavascriptChannel(name: 'CHANNEL_NAME', ...)
    flutter 绑定到您的窗口 WebView new MessageChannel 并使用您在构造函数中编写的名称(在本例中为
    CHANNEL_NAME

    因此,当我们致电
    window.CHANNEL_NAME.postMessage('Hello from JS');
    时,我们会收到我们发送的消息
WebView(
   javascriptChannels: [
     JavascriptChannel(name: 'CHANNEL_NAME', onMessageReceived: (message) {
       print(message.message);
       })
   ].toSet(),
  initialUrl: 'https://url.com',
)

我们到了。
我是颤振代码的新手
因此,如果您对此有其他更好的经验,可以写在评论中以帮助其他人!


4
投票

使用 flutter_inappwebview 包的 Javascript 回调的完整代码示例:

import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter_inappwebview/flutter_inappwebview.dart';

Future main() async {
  WidgetsFlutterBinding.ensureInitialized();
  runApp(new MyApp());
}

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => new _MyAppState();
}

class _MyAppState extends State<MyApp> {
  InAppWebViewController _webViewController;

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('InAppWebView Example'),
        ),
        body: Container(
            child: Column(children: <Widget>[
          Expanded(
            child: InAppWebView(
              initialData: InAppWebViewInitialData(data: """
<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    </head>
    <body>
        <h1>JavaScript Handlers (Channels) TEST</h1>
        <button id='test' onclick="window.flutter_inappwebview.callHandler('testFunc');">Test</button>
        <button id='testargs' onclick="window.flutter_inappwebview.callHandler('testFuncArgs', 1);">Test with Args</button>
        <button id='testreturn' onclick="window.flutter_inappwebview.callHandler('testFuncReturn').then(function(result) { alert(result);});">Test Return</button>
    </body>
</html>
                  """),
              initialOptions: InAppWebViewGroupOptions(
                  crossPlatform: InAppWebViewOptions(
                debuggingEnabled: true,
              )),
              onWebViewCreated: (InAppWebViewController controller) {
                _webViewController = controller;

                _webViewController.addJavaScriptHandler(
                    handlerName: 'testFunc',
                    callback: (args) {
                      print(args);
                    });

                _webViewController.addJavaScriptHandler(
                    handlerName: 'testFuncArgs',
                    callback: (args) {
                      print(args);
                    });

                _webViewController.addJavaScriptHandler(
                    handlerName: 'testFuncReturn',
                    callback: (args) {
                      print(args);
                      return '2';
                    });
              },
              onConsoleMessage: (controller, consoleMessage) {
                print(consoleMessage);
              },
            ),
          ),
        ])),
      ),
    );
  }
}

4
投票

有两种方式传达答案:

第一种方式从Flutter到webview(javascript、react...)

颤振侧(使用按钮或触发方法):

webViewController.evaluateJavascript('fromFlutter("pop")');

这个

fromFlutter
将是你的javascript、react等方法的名称,你也可以发送文本,在本例中为“pop”。

从 html 内的 javascript 端,在你的 body 标签中:

<script type="text/javascript">
    function fromFlutter(data) {
     // Do something
     console.log("This is working now!!!");
    }

  </script>

第二种方式从你的webview(javascript、react...)到Flutter

在您的 Webview 属性中

javascriptChannels
您可以添加:

javascriptChannels: Set.from([
     JavascriptChannel(
        name: 'comunicationname',
        onMessageReceived: (JavascriptMessage message) async {
          // Here you can take message.message and use 
          // your string from webview
        },
    )
]),

从网络视图中使用相同的通信名称“communicationname”(您可以在两个地方使用其他名称):

  window.communicationname.postMessage("native,,,pop,");

3
投票

颤振3.0.5 webview_flutter:^3.0.4 flutter_js:^0.5.0+6

使用JavascriptChannels的另一种方法是将数据从“应用程序”传输到您的网站。

飞镖:

JavascriptChannel(

          name: 'getFCMToken',
          onMessageReceived: (JavascriptMessage message) async {
            //print(message.message);

            final token = (await FirebaseMessaging.instance.getToken())!;
            final script = "var appToken =\"${token }\"";
            _webViewController.runJavascript(script);

          },
        ),

html:

<script  type = "text/javascript">
    window.onload = getFCMToken.postMessage('');
</script>

或飞镖(触发器):

OnPageFinished: (url) async {
   try {
 final token = (await FirebaseMessaging.instance.getToken())!;     
 var javascript = "var appToken=\"${token.toString()}\"";
       } catch (_) {}
}

因此,在您的网站代码中,您有一个 js var“appToken”,您可以在 PHP 或其他内容中使用它。


1
投票

如果您使用支持 web、ios 和 android 的 webviewx 插件,那么我们就可以进行双向通信。

我有一个网页,其中包含index.html和其他js,以及我想在webview中显示并在flutter和web应用程序之间进行通信的css页面。

1。从flutter到js监听器

 IconButton(
           icon: Icon(Icons.developer_mode),
           onPressed: () {
             webviewController
                 .evalRawJavascript('window.myFunction()',
                     inGlobalContext: false)
                 .then((value) => print(value));
           },
         )      

注意:myFunction 是在 javascript 或 html 页面中定义的函数,如下所示。

function myFunction() {
 alert("I am an alert box!");
 return 'working';
}

2。从js/html到flutter监听器
在 html/js 中添加带有监听器的按钮

function submitClick() {
 var data = document.getElementById('data').value;
 SubmitCallback(data) //defined in flutter
}

现在在 flutter 中(添加 dartCallback):

 WebViewX(
         javascriptMode: JavascriptMode.unrestricted,
         initialContent: '<h2> Loading </h2>',
         initialSourceType: SourceType.HTML,
         onWebViewCreated: (controller) {
           webviewController = controller;
           _loadHtmlFromAssets();
           webviewController.addListener(() {});
         },
         dartCallBacks: {
           DartCallback(
             name: 'SubmitCallback',
             callBack: (msg) {
               ScaffoldMessenger.of(context).showSnackBar(
                   SnackBar(content: Text('Submitted $msg successfully')));
             },
           ),
         },
       )

PS。快乐编码

© www.soinside.com 2019 - 2024. All rights reserved.