WKWebview - Javascript和amp;之间的复杂通信本机代码 [英] WKWebview - Complex communication between Javascript & native code
问题描述
在WKWebView中,我们可以使用webkit消息处理程序调用ObjectiveC / swift代码
例如: webkit.messageHandlers。< handler> .pushMessage(message)
In WKWebView we can call ObjectiveC/swift code using webkit message handlers
eg: webkit.messageHandlers.<handler>.pushMessage(message)
它适用于没有参数的简单javascript函数。但是;
It works well for simple javascript functions without parameters. But;
- 是否可以使用JS回调函数作为参数调用本机代码?
- 是可以从本机代码向JS函数返回一个值吗?
推荐答案
不幸的是我无法'找到原生解决方案。
Unfortunately I couldn't find a native solution.
但以下解决方法解决了我的问题
But the following workaround solved my problem
使用javascript promises&您可以通过iOS代码调用解析功能。
Use javascript promises & you can call the resolve function from your iOS code.
更新
这是如何使用承诺
在JS中
this.id = 1;
this.handlers = {};
window.onMessageReceive = (handle, error, data) => {
if (error){
this.handlers[handle].resolve(data);
}else{
this.handlers[handle].reject(data);
}
delete this.handlers[handle];
};
}
sendMessage(data) {
return new Promise((resolve, reject) => {
const handle = 'm'+ this.id++;
this.handlers[handle] = { resolve, reject};
window.webkit.messageHandlers.<yourHandler>.postMessage({data: data, id: handle});
});
}
iOS中的
in iOS
使用适当的处理程序ID调用 window.onMessageReceive
函数
Call the window.onMessageReceive
function with appropriate handler id
这篇关于WKWebview - Javascript和amp;之间的复杂通信本机代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!