js双通信java,Flutter Webview与Java双向通信

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.

解决方案

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:

Print.postMessage('Hello World being called from Javascript code');

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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值