Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

how to send message from javacript to flutter? #309

Closed
littlesalt opened this issue Jan 25, 2019 · 20 comments
Closed

how to send message from javacript to flutter? #309

littlesalt opened this issue Jan 25, 2019 · 20 comments

Comments

@littlesalt
Copy link

I want to send message from js to flutter .I try using wondow.postMessage to send message to flutter,but it fail.

@erdemyerebasmaz
Copy link

erdemyerebasmaz commented Jan 27, 2019

@littlesalt
Copy link
Author

littlesalt commented Jan 28, 2019

it is not work !

js code:

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<meta http-equiv="X-UA-Compatible" content="ie=edge">
	<title>Document</title>
</head>

<body>
	<div id="time"></div>
	<div id="message"></div>
	
	<input id="dd" style="width:160px;" placeholder="please input context to flutter"></input><br/><br/>
	<button id="button" style="background-color:#158461;height:30px;">send to flutter</button>
	
</body>

<script>

	 function sendData(data) {
	window.postMessage(data, '*');
	}
  window.onload = function () {
	  
	    document.getElementById('button').onclick = function () {
	      sendData(document.getElementById('dd').value);
	    }
	  }
</script>
</html>

flutter code:

import 'package:flutter/material.dart';
import 'package:flutter_webview_plugin/flutter_webview_plugin.dart';

class WebviewDemo extends StatefulWidget{
  @override
  _WebviewDemoState createState() =>_WebviewDemoState();

}

class _WebviewDemoState extends State<WebviewDemo>{
  final flutterWebviewPlugin = new FlutterWebviewPlugin();


  @override
  void initState() {
    super.initState();
    flutterWebviewPlugin.close();
    flutterWebviewPlugin.lightningLinkStream.listen((message){
      print(message);
    });

  }


  @override
  void dispose() {
    flutterWebviewPlugin.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return WebviewScaffold(url: 'http://192.168.3.100:8080/index7.html');
  }

}

@erdemyerebasmaz
Copy link

erdemyerebasmaz commented Jan 28, 2019

It's hard to read your comment, please format it with code tags.
I think you are sending post message but haven't set an event listener to listen to those dispatched messages. Here's how you can listen to post messages with Javascript.

You can inject this on initState(); or add it straight to your local html file. Don't forget to call the method on JavascriptInterface within this method.

flutterWebviewPlugin.onStateChanged.listen((state) async {
    if (state.type == WebViewState.finishLoad) {
        String script = 'window.addEventListener("message", receiveMessage, false);' +
            'function receiveMessage(event) {InterfaceName.methodName(event.data);}';
        flutterWebviewPlugin.evalJavascript(script);
    }
});
webView.addJavascriptInterface(new WebAppInterface(), "InterfaceName");

public class WebAppInterface {
        @JavascriptInterface
        public void methodName(String value){
            Map<String, Object> map = new HashMap<>();
            map.put("order", value);
            FlutterWebviewPlugin.channel.invokeMethod("test", map);
        }
    }

@littlesalt
Copy link
Author

@erdemyerebasmaz thanks .I have formated my code.

@littlesalt
Copy link
Author

@erdemyerebasmaz I want to received message by flutter.

@erdemyerebasmaz
Copy link

erdemyerebasmaz commented Jan 28, 2019

You need to fork and make changes on the plugin. I've added a javascript interface and passed the listened value to a stream that can be listened inside flutter.
I've shown the minimum changes here

Adjust and rename the methods according to your needs.

@littlesalt
Copy link
Author

littlesalt commented Jan 28, 2019

I used your branch,and alse add
flutterWebviewPlugin .onStateChanged.listen((state) async {...?

@erdemyerebasmaz
Copy link

erdemyerebasmaz commented Jan 28, 2019

Okay, if you are using my branch without any changes just add this to your initState();

    flutterWebviewPlugin.onStateChanged.listen((state) async {
      if (state.type == WebViewState.finishLoad) {
        String script =
            'window.addEventListener("message", receiveMessage, false);' +
                'function receiveMessage(event) {Android.getPostMessage(event.data);}';
        flutterWebviewPlugin.evalJavascript(script);
      }
    });

Try hiding instead of closing the flutterWebviewPlugin.

...
----->    flutterWebviewPlugin.close();  
    flutterWebviewPlugin.lightningLinkStream.listen((message){
      print(message);
    });

@littlesalt
Copy link
Author

@erdemyerebasmaz Thanks! I will try your suggestion.

@littlesalt
Copy link
Author

@erdemyerebasmaz Tell you good news,I have resolved this problem through your help! Thank you very much!

@Spicely
Copy link

Spicely commented Feb 25, 2019

@littlesalt ios How to solve

@sakinaboriwala
Copy link

sakinaboriwala commented Apr 20, 2019

@erdemyerebasmaz Hey, thanks a lot for this. I have a button on the page that I am loading. I am calling an onClick() event that does this:

button onclick=" MobileApp.postMessage('open_form'); "

I added this to my initState():

  void initState() {
    super.initState();
    flutterWebviewPlugin.onStateChanged.listen((state) async {
      if (state.type == WebViewState.finishLoad) {
        String script =
            'MobileApp.addEventListener("message", receiveMessage, false);' +
                'function receiveMessage(event) {Android.getPostMessage(event.data);}';
        flutterWebviewPlugin.evalJavascript(script);
      }
    });
    flutterWebviewPlugin.close();
    flutterWebviewPlugin.lightningLinkStream.listen((message) {
      print(message);
    });
  }```

But I get this error whenever I tap on the button:

 "Uncaught ReferenceError: MobileApp is not defined", source: $url (371)

I want to call a function whenever the button is tapped. Please help me if possible, it's really urgent.

@littlesalt @erdemyerebasmaz I know I am doing something wrong in my JS Script. If possible, please guide me.

@Yiend
Copy link

Yiend commented Apr 28, 2019

Where is webView.addJavascriptInterface and WebAppInterface?

@heinzan
Copy link

heinzan commented May 3, 2019

How listen Javascript function from backend to flutter

@erdemyerebasmaz
Copy link

erdemyerebasmaz commented May 22, 2019

Where is webView.addJavascriptInterface and WebAppInterface?

@DOCORE
You add it under WebviewManager.java See this commit

@erdemyerebasmaz
Copy link

erdemyerebasmaz commented May 22, 2019

How listen Javascript function from backend to flutter

@heinzan
I'm not sure what you mean but to send post messages from a webview and listen it on Flutter, check this

@erdemyerebasmaz
Copy link

@erdemyerebasmaz Hey, thanks a lot for this. I have a button on the page that I am loading. I am calling an onClick() event that does this:

button onclick=" MobileApp.postMessage('open_form'); "

I added this to my initState():

  void initState() {
    super.initState();
    flutterWebviewPlugin.onStateChanged.listen((state) async {
      if (state.type == WebViewState.finishLoad) {
        String script =
            'MobileApp.addEventListener("message", receiveMessage, false);' +
                'function receiveMessage(event) {Android.getPostMessage(event.data);}';
        flutterWebviewPlugin.evalJavascript(script);
      }
    });
    flutterWebviewPlugin.close();
    flutterWebviewPlugin.lightningLinkStream.listen((message) {
      print(message);
    });
  }```

But I get this error whenever I tap on the button:

 "Uncaught ReferenceError: MobileApp is not defined", source: $url (371)

I want to call a function whenever the button is tapped. Please help me if possible, it's really urgent.

@littlesalt @erdemyerebasmaz I know I am doing something wrong in my JS Script. If possible, please guide me.

As it says, the browser object model named MobileApp is not defined. See here. Try using window instead.

  • onclick="window.postMessage('open_form');" ....
  • String script = 'window.addEventListener ....

@sakinaboriwala
Copy link

sakinaboriwala commented Jun 6, 2019

@erdemyerebasmaz Hey, thanks a lot for this. I have a button on the page that I am loading. I am calling an onClick() event that does this:
button onclick=" MobileApp.postMessage('open_form'); "
I added this to my initState():

  void initState() {
    super.initState();
    flutterWebviewPlugin.onStateChanged.listen((state) async {
      if (state.type == WebViewState.finishLoad) {
        String script =
            'MobileApp.addEventListener("message", receiveMessage, false);' +
                'function receiveMessage(event) {Android.getPostMessage(event.data);}';
        flutterWebviewPlugin.evalJavascript(script);
      }
    });
    flutterWebviewPlugin.close();
    flutterWebviewPlugin.lightningLinkStream.listen((message) {
      print(message);
    });
  }```

But I get this error whenever I tap on the button:

 "Uncaught ReferenceError: MobileApp is not defined", source: $url (371)

I want to call a function whenever the button is tapped. Please help me if possible, it's really urgent.
@littlesalt @erdemyerebasmaz I know I am doing something wrong in my JS Script. If possible, please guide me.

As it says, the browser object model named MobileApp is not defined. See here. Try using window instead.

  • onclick="window.postMessage('open_form');" ....
  • String script = 'window.addEventListener ....

@erdemyerebasmaz Thanks for getting back to me. Earlier I was using webview_flutter but it doesn't open webviews so I am trying to switch back to this.

webview_flutter provides javascript channels property and that's how I used to listen to postMessages.

 JavascriptChannel _toasterJavascriptChannel9(BuildContext context) {
    return JavascriptChannel(
      name: 'MobileApp',
      onMessageReceived: (JavascriptMessage message) {
        print('Message received');
        ''');
      },
    );
  }

But now, I don't know how to listen to these messages with flutter_webview_plugin or atleast avoid the error that says "Uncaught ReferenceError: MobileApp is not defined", source: $url (371) so that the rest of the JS can load and work properly.

@OPY-bbt
Copy link

OPY-bbt commented Jun 26, 2019

I solved this problem in iOS and Android, I hope it's helpful。#457

@varunkumarmedam
Copy link

Can You guys provide complete flutter and js code for better understanding...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

8 participants