swift - WKWebView JS 交互

2017-09-13 20:48:51来源:CSDN作者:a1018875550人点击

分享

本文介绍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

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

result1.png

JS给APP传参数

    1. 首先注册你需要监听的js方法名
//监听jswebView.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.结果

result.png

最新文章

123

最新摄影

微信扫一扫

第七城市微信公众平台