native 端
-
初始化 wkwebview,设置 message handler
webView = WKWebView.init()
let usecc = self.webView.configuration.userContentController
usecc.add(self, name: "testecho") -
实现
WKScriptMessageHandler
协议extension ViewController: WKScriptMessageHandler {
func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
mylog("\(self.sendCount) call native , message is \(message.name),")
}
} -
执行JS 代码
//jsStr = "echo(\"wordword\")"
self.webView.evaluateJavaScript(jsStr) { (result, err) in
self.mylog("\(self.sendCount) \(jsStr.count) bytes callback, result: \(result), err: \(err)")
}前端
<!DOCTYPE html>
<html>
<script type="text/javascript">
function echo(str) {
console.log(str);
window.webkit.messageHandlers.testecho.postMessage(str);
}
</script>
<body>
<input type="button" onClick="echo('toast clicked')" value="toast">
<input type="button" onClick="echo('alert clicked')" value="Alert">
</body> </html>
分析
native 端注册了 testecho
的messageHandler,所以 JS 可以通过 window.webkit.messageHandlers.testecho.postMessage
来回调客户端,和文档中说的一样。
Adding a script message handler with name name causes the JavaScript function window.webkit.messageHandlers.name.postMessage(messageBody) to be defined in all frames in all web views that use the user content controller.