Skip to content
Advertisement

How to get javascript console.log in flutter webview

I created a simple javascript that sends a response through console.log(); and I have a flutter WebView that loads the URL and in my flutter android studio console I get this response as I/chromium(27778): [INFO:CONSOLE(20)] "My name", source: https://response_test.php but I’m looking for a way to receive this response in my flutter app so I can use the response to navigate user to another page. My code looks like below:

My javascript code:

<?php 

$MyPHPStringVar = "My name";

?>

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title></title>

<script type="text/javascript">
    var MyJSStringVar = "<?php Print($MyPHPStringVar); ?>";
    console.log(MyJSStringVar);             
</script>

</head>
<body>

</body>

</body>
</html>

And my flutter webview is like this:

      WebView(
          javascriptMode:JavascriptMode.unrestricted,
          initialUrl: "https://hobber.ae/api/webview_response_test.php",
          onWebViewCreated: (WebViewController webViewController) {
            _controller.complete(webViewController);
          },
          
        ),

I want a way to receive my response inside my activity so I can make use of thhe data received.

Advertisement

Answer

After checking different option to achieve this I was able to come up with a solution which is using Print.postMessage instead of using console.log() and my javascript code looks like below:

<script type='text/javascript'>
    Print.postMessage('<?php Print($MyPHPStringVar); ?>');
</script>

And in my flutter webview I got the value in onMessageReceived: and my final flutter code is like below:

Stack(children: [

     javascriptChannels:Set.from([
            JavascriptChannel(
                name: 'Print',
                onMessageReceived: (JavascriptMessage message) {
                  print(message.message);
                })
          ]),

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement