androidflutterwebview-flutter

Flutter postMessages not working on android emulator


I'm developing a webview app using flutter webview_flutter lib. When I send postMessages on IOS it works fine, but when testing on android emulator the terminal print an error message Uncaught Error: Method not found when executing the function postMessage.postMessage(JSON.stringify(obj), "*");.

Here is my webview code:

  WebView(
    javascriptMode: JavascriptMode.unrestricted,
    debuggingEnabled: true,
    initialUrl: '<url_to_my_template>',
    onPageStarted: (url) {},
    onPageFinished: (url) async {},
    javascriptChannels: <JavascriptChannel>{
      JavascriptChannel(
        name: 'postMessage',
        onMessageReceived: (message) async {
          print('postMessage: ${message.message}');
        },
      ),
    },
    onWebViewCreated: (WebViewController controller) {
      setState(() {
        _controller = controller;
      });
    },
  ),

And this is my js file:

function troca_dados_envia(obj){
    "use strict";
    //Flutter
    postMessage.postMessage(JSON.stringify(obj),  "*");
}

I tried the code above, and I was expecting to work on both Android and IOS devices, but it turns out that only IOS devices listen and send post messages.


Solution

  • We also went in circles with this, even though WebView on Android should support the full parameters of window.postMessage() it throws an error when defining the target origin.

    Try just

    postMessage.postMessage(JSON.stringify(obj));
    

    Also for anybody else who gets stuck - you must ensure that the data being sent is a String, even though it seems other formats should be supported - it seems only Strings are sent reliably.