I have an html file that I am loading in Flutter webview using flutter_webview_plugin. I am using evalJavascript to call function in my javascript code, meaning flutter(dart)->js. However, I also need some way to communicate back something to flutter(dart) layer, meaning js->flutter(dart).
I have tried using - webkit.messageHandlers.native - window.native to support both platforms(Android,iOS) checking if those are available in JS. But, those comes as undefined. Using following code to get instance of native handler in JS.
typeof webkit !== 'undefined' ? webkit.messageHandlers.native : window.native;
And even if I get that instance and post message using it, not sure how to handle it in flutter(dart) layer. I may need to use platform channels. Not sure, if I am in the right direction.
Is there any way through which I can do that? I have evaluated interactive_webview plugin. It works fine on Android. But, it has swift versioning issue and don't want to proceed further with that.
Any help would be appreciated.
With this article, we'll look at some examples of Flutter Inject Javascript In Flutter Webview problems in programming. onLoadStop: (controller, url) async { var result = await controller. evaluateJavascript(source: "1 + 1"); print(result.
The Javascript runtimes runs synchronously through the dart ffi. So now you can run javascript code as a native citzen inside yours Flutter Mobile Apps (Android, IOS, Windows, Linux and MacOS are all supported).
You can pass route params to an angular page, so if you have the data going from your flutter app to a database, say Firebase, then you can pass the specific document ID as a route param in flutter webview, and any data you are passing in flutter will auto sync up to the route that you have called in angular.
Here is an example of communication from Javascript code to flutter.
In Flutter build your WebView like :
WebView( initialUrl: url, javascriptMode: JavascriptMode.unrestricted, javascriptChannels: Set.from([ JavascriptChannel( name: 'Print', onMessageReceived: (JavascriptMessage message) { //This is where you receive message from //javascript code and handle in Flutter/Dart //like here, the message is just being printed //in Run/LogCat window of android studio print(message.message); }) ]), onWebViewCreated: (WebViewController w) { webViewController = w; }, )
and in Your HTMLfile:
<script type='text/javascript'> Print.postMessage('Hello World being called from Javascript code'); </script>
When you run this code, you shall be able to see log "Hello World being called from Javascript code" in the LogCat/Run window of android studio.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With