Flutter webview two way communication

前端 未结 3 655
终归单人心
终归单人心 2020-12-03 14:31

I have an html file that I am loading in Flutter webview using flutter_webview_plugin. I am using evalJavascript to call function in my javascript code, meaning flutter(dart

3条回答
  •  [愿得一人]
    2020-12-03 15:11

    You can try my plugin flutter_inappbrowser (EDIT: it has been renamed to flutter_inappwebview) and use addJavaScriptHandler({@required String handlerName, @required JavaScriptHandlerCallback callback}) method (see more here).

    An example is presented below. On Flutter side:

    ...
    
    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
          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}");
      },
    ),
    
    ...
    

    On JavaScript side (for example a local file assets/index.html inside the assets folder):

    
    
        
            
            
            
            Flutter InAppBrowser
    
            ...
    
        
        
    
            ...
    
            
        
    
    

    On Android Studio logs you will get:

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

提交回复
热议问题