Home > OS >  Flutter webview with custom javascriptInterfaceAdapter or invoke JS using webview controller
Flutter webview with custom javascriptInterfaceAdapter or invoke JS using webview controller

Time:12-18

I have an old java project that performs in andorid webview with addJavascriptInterface

mWebView.addJavascriptInterface(new JavascriptAdapter(), "AndroidFunctions");

Within JavascriptAdapter class there is several @JavascriptInterface functions. as example

class JavascriptAdapter {
    @JavascriptInterface
    getMacAddress(){
        DeviceInfo deviceInfo = new DeviceInfo(activity);
        return deviceInfo.getMacAddress();
  }
}

now after opening the webview within android applications, using JS we can access that function like this way -

var strMacAddress = AndroidFunctions.getMACAddress();

Now I would like to achieve this thing on flutter. for that, I am using the flutter inAppWebview plugin.

As well as I am new to Flutter, can someone please help me to achieve this thing?

CodePudding user response:

Please take a look in this documentation for InAppWebView.

JavScriptInterface are normally used to call native methods from webview. I am assuming that the webpage calls the method, so, you have to return the Mac Address as it is presented in the documentation. But you need to change the way for calling the method for flutter by adding this sample(provided in documentation) to you webpage source.

<script>
        window.addEventListener("flutterInAppWebViewPlatformReady", function(event) {
            window.flutter_inappwebview.callHandler('handlerFoo')
              .then(function(result) {
                // print to the console the data coming
                // from the Flutter side.
                console.log(JSON.stringify(result));
                
                window.flutter_inappwebview
                  .callHandler('handlerFooWithArgs', 1, true, ['bar', 5], {foo: 'baz'}, result);
            });
        });
    </script>

CodePudding user response:

You can inspect this Webview from google chrome.

chrome://inspect/#devices

and don't forget to add flutter_inappwebview: ^5.3.2 in your pubspec.yaml

the answer is already given in this link I have just added for a quick look on SO.

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

Future main() async {
  WidgetsFlutterBinding.ensureInitialized();

  if (Platform.isAndroid) {
    await AndroidInAppWebViewController.setWebContentsDebuggingEnabled(true);
  }
  
  runApp(new MyApp());
}

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

class _MyAppState extends State<MyApp> {

  InAppWebViewGroupOptions options = InAppWebViewGroupOptions(
      android: AndroidInAppWebViewOptions(
        useHybridComposition: true,
      ),);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
          appBar: AppBar(title: Text("JavaScript Handlers")),
          body: SafeArea(
              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</h1>
        <script>
            window.addEventListener("flutterInAppWebViewPlatformReady", function(event) {
                window.flutter_inappwebview.callHandler('handlerFoo')
                  .then(function(result) {
                    // print to the console the data coming
                    // from the Flutter side.
                    console.log(JSON.stringify(result));
                    
                    window.flutter_inappwebview
                      .callHandler('handlerFooWithArgs', 1, true, ['bar', 5], {foo: 'baz'}, result);
                });
            });
        </script>
    </body>
</html>
                      """
                    ),
                    initialOptions: options,
                    onWebViewCreated: (controller) {
                      controller.addJavaScriptHandler(handlerName: 'handlerFoo', callback: (args) {
                        // return data to the JavaScript side!
                        return {
                          'bar': 'bar_value', 'baz': 'baz_value'
                        };
                      });

                      controller.addJavaScriptHandler(handlerName: 'handlerFooWithArgs', callback: (args) {
                        print(args);
                        // it will print: [1, true, [bar, 5], {foo: baz}, {bar: bar_value, baz: baz_value}]
                      });
                    },
                    onConsoleMessage: (controller, consoleMessage) {
                      print(consoleMessage);
                      // it will print: {message: {"bar":"bar_value","baz":"baz_value"}, messageLevel: 1}
                    },
                  ),
                ),
              ]))),
    );
  }
}
  • Related