[英]How to write an async counter, i.e. a counter with sync interface for async code, using only the native Promise?
[英]In iOS 13 and below, how can WKWebView call an async Javascript function (i.e. one that returns a promise)?
iOS 14 有这个 API ,但是如何在 iOS 13 或更低版本中实现?
例如,假设 JS 有一个 function 定义为:
function upperCaseAsync(text) {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve(text.toUpperCase());
}, 300);
});
}
如何调用和处理生成的 promise 的结果? 我尝试使用同步 API ,但它会引发错误:
错误域 = WKErrorDomain 代码 = 5“JavaScript 执行返回了不支持类型的结果”
您需要注册回调处理程序并将您的 JS function 从返回Promise
为发布webkit
消息: webkit.messageHandlers['smth'].postMessage('some info if needed')
let script = WKUserScript(source: <your js code>, injectionTime: .atDocumentStart, forMainFrameOnly: false)
<your web view>.configuration.userContentController.addUserScript(script)
<your web view>.configuration.userContentController.add(<whatever>, name: "smth")
extension <whatever>: WKScriptMessageHandler {
func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
switch message.name {
case "smth":
break // do smth
default:
return
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.