How to add JavaScriptInterface in Flutter WebView or InAppWebView?

Viewed 4256

In Android I can add javascript interface:

class JsInterface(private val onClose: () -> Unit) {
    @android.webkit.JavascriptInterface    
    fun close() {
        onClose()    
    }
}
...
addJavascriptInterface(JsInterface { this@WebViewActivity.finish() }, "client")

How can I do the same in Flutter WebView or InAppWebView or other packages?

1 Answers

I suggest you to read this article, where they take a closer look at flutter_inappwebview. But try this code example for quick answer:

              InAppWebView(
                initialUrl: 'url',
                onWebViewCreated: (controller) =>
                    control.webController = controller
                      ..addJavaScriptHandler(
                        handlerName: 'serverSideJsFuncName',
                        callback: (data) {
                          // Catch and handle js function
                        },
                      ),
              )

On the other hand, if you want to update server side JavaScript you can do it via InAppWebViewController like this:

  Future<void> evalJs(dynamic param) async {
    await webController.evaluateJavascript(
        source: "window.someFuncName( '$param ');");
  }

Related