3

In Android I can add javascript interface:

class JsInterface(private val onClose: () -> Unit) {
    @android.webkit.JavascriptInterface    
    fun close() {
        onClose()    
    }
}
...
addJavascriptInterface(JsInterface { [email protected]() }, "client")

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

1 Answer 1

4

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

Sign up to request clarification or add additional context in comments.

5 Comments

Thank you! On the js side runs this code: " if(window.client) window.client.close() " If just write " ..addJavaScriptHandler(handleName: 'close', callback: (data) {...}) " it doesn't work. Do you know how to do it?
I am sorry but i don't think i can. Try to debug your actions from app against server. We also had some problems until we find correct way to access functions by their name from each mobile and backend. Try it with article i posted at JavascriptHandlers section.
Maybe you know how to add js interface via evaluate?
Evaluate is used to invoke some javascript functions on server from app. If you want to handle such function you have to define it like this window.addEventListener("flutterInAppWebViewPlatformReady", function(event) { window.flutter_inappwebview.callHandler('handlerFoo') .then(function(result) { // print to the console the data coming window.flutter_inappwebview .callHandler('handlerFooWithArgs', 1, true, ['bar', 5], {foo: 'baz'}, result); }); });
Each function must have "addEventListener("flutterInAppWebViewPlatformReady",..." and window.flutter_inappwebview.callHandler('handlerFoo') to be registered by that WebView. Then you can invoke it by calling method as i wrote in example, but instead of "someFuncName" you will enter "handlerFoo". After this you should be able to handle JS from app.

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.