4

I am using webview_flutter with version 3.0.0 in my app. I have heavy usage of two-way communication between flutter and javascript. Everything works on debug mode nicely. But, after I build the APK started to get some errors in the javascript channel. I tried with flutter run --release and got the same error.

In my web application (ReactJs), I am using channels in this way:

index.html

<div id="root">
    <script>
        function sendToFlutter(message) {
            if (flutterChannel) {
                flutterChannel.postMessage(message);
            }
        }
    </script>
</div>

calling is from React component like this:

window.sendToFlutter("hello-world");

My Webview setup from Flutter end:

Completer<WebViewController> webViewCompleter = Completer<WebViewController>();

WebView(
    debuggingEnabled: false,
    initialUrl: "https://example.com",
    javascriptMode: JavascriptMode.unrestricted,
    onWebViewCreated: (WebViewController webViewController) {
        webViewCompleter.complete(webViewController);
    },
    javascriptChannels: <JavascriptChannel>{
        JavascriptChannel(
        name: "flutterChannel",
        onMessageReceived: (JavascriptMessage message) {

          if (message.message == "hello-world") {
            // Do something
          }
        })
    },
    navigationDelegate: (NavigationRequest request) {
        if (request.url.startsWith('https://www.youtube.com/')) {
            return NavigationDecision.prevent;
        }
        
        return NavigationDecision.navigate;
    },
    gestureNavigationEnabled: true,
    zoomEnabled: false,
    userAgent: Platform.isAndroid ? kAndroidUserAgent : kIosUserAgent,
);

When I call the channel from ReactJs, then I am getting this error:

TypeError: flutterChannel.postMessage is not a function
Md Abdul Halim Rafi
  • 1,810
  • 1
  • 17
  • 25

1 Answers1

1

According to alexbatalov's research in https://github.com/flutter/flutter/issues/92548, the current workaround is to do the following:

Create android/app/proguard-rules.pro. At minimum you need to have a rule for JavascriptInterface, but I recommend to copy entire proguard-android.txt, given the fact that you don’t have these rules.

# Preserve annotated Javascript interface methods.
-keepclassmembers class * {
    @android.webkit.JavascriptInterface <methods>; 
}
Gary Qian
  • 2,984
  • 3
  • 10
  • 7