Flutter webview with custom javascriptInterfaceAdapter or invoke JS using webview controller

1,756

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>
Share:
1,756
Atiar Talukdar
Author by

Atiar Talukdar

Updated on December 02, 2022

Comments

  • Atiar Talukdar
    Atiar Talukdar over 1 year

    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.

    • Ruchit
      Ruchit over 2 years
      try to use webview_flutter official plug in on pub.dev
    • Atiar Talukdar
      Atiar Talukdar over 2 years
      tried but was unable to pass the function.