WKWebView 里 JS 和 native 通信的例子

native 端

  1. 初始化 wkwebview,设置 message handler

    webView = WKWebView.init()
    let usecc = self.webView.configuration.userContentController
    usecc.add(self, name: "testecho")
  2. 实现 WKScriptMessageHandler协议

    extension ViewController: WKScriptMessageHandler {
    func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
    mylog("\(self.sendCount) call native , message is \(message.name),")
    }
    }
  3. 执行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.

参考

上一篇:将本地项目上传到码云


下一篇:【动态规划】Column Addition @ICPC2017Tehran/upcexam5434