欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

swift - WKWebView JS 交互

程序员文章站 2024-02-05 20:53:22
...

本文介绍WKWebView怎么与js交互,至于怎么用WKWebView这里就不介绍了

html代码

<html>
    <meta charset="UTF-8">
    <head>
        <title>
            H5测试
        </title>
    </head>
    <body>
        <h1 align="center">标题1(App调用Js使标题变成红色)</h1>
        <script>
             //js调用APP-传单个参数
             function callNativeApp(){
                try{
                    webkit.messageHandlers.callbackHandle.postMessage("Hello World")
                }catch(error){
                    console.error('The native context not exist ')
                }
            }
            //js调用APP-传多个参数
            function callNativeApp2(){
                try{
                    webkit.messageHandlers.callbackHandle2.postMessage({key: "Hello", value: "World"})
                }catch(error){
                    console.error('The native context not exist ')
                }
            }
            //APP调用js
            function changeHead(){
                document.querySelector('h1').style.color = "red"
            }
            </script>

            <button style="text-align:center;height:50px;width:200px;font-size:16px" onclick="callNativeApp()">调用APP(单个参数)</button>

            <button style="text-align:center;height:50px;width:220px;font-size:16px" onclick="callNativeApp2()">调用APP(多个个参数)</button>
    </body>
</html>

APP调JS

  • 代码
//调用js
webView.evaluateJavaScript("changeHead()", completionHandler: {
            (any, error) in
            if (error != nil) {
                Log.error("\(error)")
            }
        })
  • 结果

swift - WKWebView JS 交互

JS给APP传参数

    1. 首先注册你需要监听的js方法名
//监听js
webView.configuration.userContentController.add(self, name: "callbackHandle")
webView.configuration.userContentController.add(self, name: "callbackHandle2")
  • 2.继承WKScriptMessageHandler 并重写userContentController方法,在该方法里接收JS传来的参数
@available(iOS 8.0, *)
func userContentController(_ userContentController: WKUserContentController,
                               didReceive message: WKScriptMessage) {

        switch message.name {
        case "callbackHandle":
            //单个参数
            Log.info("\(message.body)")
        case "callbackHandle2":
            //多个参数
            if let dic = message.body as? NSDictionary {
                let key: String = (dic["key"] as AnyObject).description
                let value: String = (dic["value"] as AnyObject).description

                Log.info("key: \(key)")
                Log.info("value: \(value)")

            }
        default: break
        }

    }
  • 3.结果

swift - WKWebView JS 交互