在 iOS 13 及以下版本中,WKWebView 如何调用异步 Javascript 函数(即 returns 承诺的函数)?

In iOS 13 and below, how can WKWebView call an async Javascript function (i.e. one that returns a promise)?

iOS14有this API,但是iOS13以下如何实现呢?

例如,假设JS有一个函数定义为:

function upperCaseAsync(text) {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve(text.toUpperCase());
    }, 300);
  });
}

如何调用和处理resulting promise的结果?我尝试使用 synchronous API,但它会引发错误:

Error Domain=WKErrorDomain Code=5 "JavaScript execution returned a result of an unsupported type"

您需要注册回调处理程序并将您的 JS 函数从返回 Promise 更改为 post 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
        }
    }
    
}