1

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.

also, I have tried flutter_webview, WKWebview.

2
  • try to use webview_flutter official plug in on pub.dev Commented Dec 17, 2021 at 3:12
  • tried but was unable to pass the function. Commented Dec 17, 2021 at 4:07

2 Answers 2

2

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>
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.