How to add JavaScriptInterface in Flutter WebView or InAppWebView?

3,565

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

Share:
3,565
Maxim
Author by

Maxim

Updated on December 24, 2022

Comments

  • Maxim
    Maxim over 1 year

    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?

  • Maxim
    Maxim over 3 years
    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?
  • David Sedlář
    David Sedlář over 3 years
    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.
  • Maxim
    Maxim over 3 years
    Maybe you know how to add js interface via evaluate?
  • David Sedlář
    David Sedlář over 3 years
    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); }); });
  • David Sedlář
    David Sedlář over 3 years
    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.